Reading, Writing, and Flipping Bits in C

Bitwise programming techniques (manipulating binary numbers) is simple in theory, but it’s often hard to remember how to do specific tasks if you don’t do them often. Recently in my microcontroller programming endeavors (where you’re pressed to conserve every bit of memory) 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 to assign a whole variable to the task (even a char, the smallest variable in C is a waste because it uses 8 bits of memory!). When cramming multiple values into individual variables, it’s nice to know how to manipulate each bit of a variable.

Questions like “how do I retrieve the value of a certain bit in a variable”, “how do I set the value of a certain bit in a variable”, and “how do I flip a certain bit in a variable” can eventually be answered by twiddling around with bitwise operators in C, but often the solutions you randomly discover this way are not elegant or efficient. This afternoon I ran across the following chart on an Arduino help site and although I’m not a fan of Arduino, I can certainly appreciate the chart. I hope you find it as useful as I did.

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.


Leave a Comment