When should you use bitwise operators?
How many basic bitwise operations are there?
Source code that does bit manipulation usually makes use of the basic bitwise operations: AND, OR, XOR, NOT, and bit shifts.
As a reminder, here are the
truth tables
:
AND: 1 & 1 = 1, else are all 0
OR: 0 | 0 = 0, else are all 1
XOR: 1 ^ 0 = 0 ^ 1 = 1, else are 0
NOT: !0 = 1, !0 = 1
Left Shifts: 0001 << 1 = 0010, general bit_arg<<shift_arg equivalent to multiplication by 2^shift_arg
Right Shifts: 0010 >> 1 = 0001, general bit_arg>>shift_arg equivalent to division by 2^shift_arg
Some useful operations when coding.
Set union: A | B
Set intersection: A & B
Set subtration: A & ~B
Set negation: ALL_BITS_ONE ^ A
Assign 2^bit to be 1: A |= 1<<bit
Assign 2^bit to be 0: A &= ~(1<<bit)
Check if 2^bit is 1: (A & 1<<bit) != 0