C/C++ compound binary logic operations

      No Comments on C/C++ compound binary logic operations

I’ve always had trouble reading and understanding compound binary operations fluently. Whenever they appear in a piece of code, I have to decode them to actually understand what they are doing. This is mainly due to the fact that I infrequently work close to hardware were heavy bit manipulation is a daily occurrence. I won’t bother you with the truth tables of regular bitwise operators, but here’s list of combined bit operations that come in quite handy:

Setting a bit

foo |= 0x01;

The OR operation is used to set a particular bit that is specified in a BIT MASK. The bit mask is usually specified in hex. In this example it is 0x01 which indicates the first bit.

Clearing a bit

To clear bit 0 in foo, two different bit operations are required:

foo &= ~0x01;

This example uses the AND and the NOT operator. The NOT operator is used, because most programmers like to specify a mask, wherein the bit that should be changed, is set. You could of course just use a mask, wherein the bits that should be changed are unset, therefore eliminating the requirement for the NOT operator (note that this is highly uncommon though).

Flipping a bit

Another very useful tool is the XOR operator:

foo ^= 0x01;

This toggles the first bit, independent of its current state and leaves all other bits unchanged.

Checking if a bit is set

Because a statement anything other than zero is considered TRUE in C/C++ (and probably every other programming language, too), you can use

if(foo & 0x01) {

to check, whether the first bit is set or clear.

Dynamically building a bit mask

Because it is much easier to specify the bit number that should be changed rather than the actual bit mask, programmers usually build up the bit mask dynamically. This is done by left-shifting 0x01 n-times. For example, to build a bit mask that has bit number 7 set, you left-shift 0x01 seven times:

(0x01 << 7)

To build a bit mask that has the first bit (bit number 0) set, you’d shift 0x01 zero times:

(0x01 << 0)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.