March 15th, 2005 —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
One Response to “Bit Manipulation in C/C++”
|
|
Quoth bit manipulation « brewing a storm in a teacup
August 22nd, 2007 at 11:09 am [...] 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 [...] |