Set, clear and toggle
To change chosen bits, build a mask with 1s exactly where you want to act, then combine: OR sets those bits, AND with the inverted mask clears them, and XOR toggles them. A mask of k ones is (1 << k) - 1, shifted to where it is needed.
How to recognise it
- The question asks to set, clear, flip or copy particular bits or a range of bits.
- Several yes/no flags are packed into one integer.
The idea in one picture
Think of the bits as a row of light switches. A mask is a stencil that covers only the switches you want to touch. OR pushes them on, AND with the inverted stencil pushes them off, and XOR flips them.
| Action on the masked bits | Code |
|---|---|
| set to 1 | n | mask |
| clear to 0 | n & ~mask |
| toggle | n ^ mask |
| read | (n & mask) != 0 |
Building masks
| Mask | Code |
|---|---|
bit i only | 1 << i |
the lowest k bits | (1 << k) - 1 |
bits l..r (counting from 1) | ((1 << (r - l + 1)) - 1) << (l - 1) |
Common mistakes
- Mixing 0-based and 1-based bit positions.
- Using
^when the question says "set", which turns already-set bits off. - Building a 32-bit-wide mask with
1 << 32, which overflows; use a 64-bit shift.
Problems
- Copy set bits in a rangemediumguide ready