BitsBit Manipulation
Bitwise Operators
The six primitive operations on the binary representation of integers: AND, OR, XOR, NOT, left shift and right shift.
a
0
7
0
6
0
5
0
4
1
3
1
2
0
1
0
0
= 12
b
0
0
0
0
1
0
1
0
= 10
1/8Start with a=12 (00001100) and b=10 (00001010). Bit 0 on the right is the least significant; each operator works bit by bit.
Bits being examinedResult bit is 1Result bit is 0
PseudocodeLearn Bitwise Operators →
1a & b # 1 only where both bits are 12a | b # 1 where either bit is 13a ^ b # 1 where bits differ4~a # flip every bit (8-bit view)5a << 1 # shift left: doubles, drops the top bit6a >> 1 # shift right: halves, drops the low bitVariables
a12
b10
Complexity
best O(1)
avg O(1)
worst O(1)
space O(1)
Speed