Bit operations: Clear a bit | ||||||||||||
Problem: given int i, set bit n to 0 | ||||||||||||
bn | b0 | |||||||||||
i | 0000 | 0000 | 0000 | 0000 |
|
0000 | 0000 | 0010 | ||||
bit n | ||||||||||||
How can we make sure this bit is 0 (and not affect any other bits)? | ||||||||||||
We can use & operator with a "mask": | ||||||||||||
mask | 1111 | 1111 | 1111 | 1111 |
|
1111 | 1111 | 1111 | ||||
i &= mask; | ||||||||||||
What is the problem with this? | ||||||||||||
Answer: | ||||||||||||
i &= ~(1 << n); | /* idiom */ | |||||||||||
Shift 1 bit n places to the left | ||||||||||||
Flip bits to get all 1's except 0 in bit n | ||||||||||||
Apply & operator to clear bit n | ||||||||||||