Tales of a Dreamer

bit manipulation

August 23, 2007 · Leave a Comment

found this useful article at http://bogomip.net/blog/bit-manipulation-in-cc/. no smart-ass comments. just facts and examples. i’m posting it here so that when i need it (again) in the future, i’ won’t have to google it.

To set bits: OR with all 0’s except 1 where the bit should be set.

a = 0100 b = 0010 a |= b makes a = 0110

 To clear bits: AND with all 1’s except 0 where the bit should be cleared.

a = 0100 b = 1011 a &= b makes a = 0000

To test bits: AND with all 0’s except 1 where the bit should be tested.

 a = 0101 b = 0100 if((a &= b) == b) then a has bits in b set

Categories: programming