Bitwise operation

Basics

Operator Meaning Example
~ invert 0->1, 1->0
<< arithmetic shift to left (signed) 101->010
>> arithmetic shift to right (signed) 101->110 (preserve sign)
>>> logical right shift (unsigned) 101->010
& AND 0&0=0, 0&1=0, 1&0=0, 1&1=1
! OR 0^0=0, 0^1=1, 1^0=1, 1^1=1
^ XOR 0!0=0, 0!1=1, 1!0=1, 1!1=0
  • Note: OR should be "|", I put "!" here since it is difficult to write "|" in tables.
  • Do not have <<< since unsigned left shift is same as signed left shift

Trickes

x ^ 0s = x x & 0s = 0 x ! 0s = x
x ^ 1s = ~x x & 1s = x x ! 1s = 1
x ^ x = 0 x & x = x x ! x = x

Reference