Flipping Bits in C

Bitwise programming techniques (manipulating the 1s and 0s of binary numbers) are simple, but hard to  remember if you don’t use them often. Recently I’ve needed to perform a lot of bitwise operations. If I’m storing true/false (1-bit) information in variables, it’s a waste of memory to assign a whole variable to the task (the smallest variable in C is a char, and it contains 8 bits). When cramming multiple values into individual variables, it’s nice to know how to manipulate each bit of a variable.

y = (x >> n) & 1; // stores nth bit of x in y.  y becomes 0 or 1.

x &= ~(1 << n); // forces nth bit of x to be 0.  all other bits left alone.

x &= (1 << (n + 1)) - 1; // leaves lowest n bits of x; all higher bits set to 0.

x |= (1 << n); // forces nth bit of x to be 1.  all other bits left alone.

x ^= (1 << n); // toggles nth bit of x.  all other bits left alone.

x = ~x; // toggles ALL the bits in x.