BitsBit Manipulation
Set, Clear, Toggle, Test a Bit
The four single-bit primitives: set with OR, clear with AND-NOT, toggle with XOR, test with AND on a shifted 1.
n
0
7
0
6
1
5
0
4
1
3
1
2
0
1
0
0
= 44
1/7n = 44 (00101100). We want to manipulate bit k=1, which currently is 0.
Bit kBit set to 1Bit cleared to 0
PseudocodeLearn Set, Clear, Toggle & Test a Bit →
1mask = 1 << k2set = n | mask3clear = n & ~mask4toggle = n ^ mask5test = (n >> k) & 1Variables
n44
k1
Complexity
best O(1)
avg O(1)
worst O(1)
space O(1)
Speed