Bit operation in C++
Bit operator
operator | function | example |
---|---|---|
« | left shift | 0001 –> 0010 |
» | right shift | 0010 –> 0001 |
& | and (bit by bit) | 1100 & 1010 = 1000 |
| | or (bit by bit) | 1010 | 0101 = 1111 |
~ | reverse | ~0000 = 1111 |
^ | XOR | 0110 ^ 1100 = 1010 |
Operator: &
x is a bit
x & 1 = x
x & 0 = 0
Usually use & as a filter. Suppose we have a number is X, X & 0011 will get the last two bits of X.