Bit operations: Set a bit | |||||||||||||
Problem: given int i, set bit n to 1 | |||||||||||||
bn | b0 | ||||||||||||
i | 0000 | 0000 | 0000 | 0000 |
|
0000 | 0000 | 0010 | |||||
bit n | |||||||||||||
How can we make sure this bit is set to1 (and not affect any other bits)? | |||||||||||||
We can use | operator with a "mask": | |||||||||||||
mask | 0000 | 0000 | 0000 | 0000 |
|
0000 | 0000 | 0000 | |||||
i |= mask; | |||||||||||||
What is the problem with this? | |||||||||||||
Answer: | |||||||||||||
i |= (1 << n); | /* idiom */ | ||||||||||||
(Shift 1 bit n places to the left, then apply or operator to the result and i). | |||||||||||||