home

programming

bitwise

& - and
| - or
^ - xor
~ - not
<< - shift left
>> - shift right
((x & 1) == 0) # check if x is even
(x & (1 << n)) # check if n-th bit is set
x | (1 << n) # set n-th bit
x & ~(1 << n) # unset n-th bit
x ^ (1 << n) # toggle n-th bit
x & (x - 1) # turn off rightmost 1-bit
x & (-x) # isolate rightmost 1-bit
x | (x - 1) # right propagate rightmost 1-bit
~x & (x + 1) # isolate rightmost 0-bit
x | (x + 1) # turn on rightmost 0-bit

bits