0PricingLogin
Competitive Programming Academy · Lesson

Set, Clear & Toggle a Bit

Edit a single bit with masks.

Edit One Bit at a Time

Sometimes you need to change a single bit without touching the others. The trick is building a mask that targets exactly the bit you want. 🎯

Build a Single-Bit Mask

Shift 1 to the position you care about and you get a mask with one bit on. Position 0 is the rightmost bit.

mask = 1 << 3  # 0b1000, targets bit 3

All lessons in this course

  1. AND, OR, XOR & Shifts
  2. Set, Clear & Toggle a Bit
  3. Count Bits and Lowest Set Bit
  4. Bitmasks as Tiny Sets
← Back to Competitive Programming Academy