Learn / Bit manipulation

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 bitsCode
set to 1n | mask
clear to 0n & ~mask
togglen ^ mask
read(n & mask) != 0

Building masks

MaskCode
bit i only1 << 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

0 of 1 solved

Check yourself

How do you set bit i of n (make it 1)?

How do you clear bit i of n (make it 0)?

Which mask has ones in bits 2, 3 and 4 (counting from 0)?