# Bit magic in C (and C++)

Tips and trick for embedded C/C++

# Set a bit

// Set one bit high at position "bit" in input and store to output
output = input | (1 << bit);
// Shorthand
variable |= (1 << bit);
// Multiple bits
variable |= (0b101 << bit);


# Clear a bit

// Clear one bit high at position "bit" in input and store to output
output = input & ~(1 << bit);
// Shorthand
variable &= ~(1 << bit);
// Multiple bits
variable &= ~(0b101 << bit);


# Toggle a bit

// Clear one bit high at position "bit" in input and store to output
output = x ^ (1 << bit);
// Shorthand
variable ^= (1 << bit);
// Multiple bits
variable ^= (0b101 << bit);


# Math

// Division using bitshift
output = input >> 1; // Divide by 2
output = input >> 2; // Divide by 4
output = input >> 3; // Divide by 8
// Multiply using bitshifting
output = input << 1; // Multiply by 2
output = input << 2; // Multiply by 4
output = input << 3; // Multiply by 8


# Set X number of bits high.

output = (0b1 << X) -1;


# Minimum required bits

$$bits = { log(number) \over log(2) }$$ Since you can not use fractions of a bit the number should be rounded up.

# Miscellaneous

// Check if number is ODD
if( (num & 1) == 1) {};
// Flip signed integer
num = ~num + 1;
// Is an integer a power of two?
num > 0 && (num & (num - 1)) == 0;
//Clear all bits from 0 to N
mask = ~((1 << n+1 ) - 1); 