C/C++ Bit Manipulation
Posted in
Afternoon watch, 1 bell (12:30 pm)

I don't use this enough to keep it in my head, so I wrote it down here. Next time I can look it up quickly.

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

1 Comment »

One Response to “C/C++ Bit Manipulation”

  1. [...] 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 [...]

Leave a Reply