Module 3 · Logic and bit operations · Lesson 4 of 6
Working with single bits
The real power of bitwise operators is targeting one bit while leaving the rest alone. The tool for that is a mask: a number with a single 1 in the position you care about, built easily with a shift — 1 << n puts a 1 in slot n.
Switch on bit 2 with a mask
x0001
1 << 20100
x | (1<<2)0101
Same trick, different operator: & a mask to check a bit, & ~mask to clear it, ^ to flip it.
Pair a mask with the right operator and you get four precise moves on a single bit:
- Set it to 1: x | (1 << n)
- Check if it's 1: x & (1 << n)
- Clear it to 0: x & ~(1 << n)
- Flip it: x ^ (1 << n)
Run it yourselfruns in your browser · Python
main.py
This is how a single integer can pack dozens of on/off flags — one per bit — which is why bit masks show up in graphics, networking, hardware and file permissions. The last piece of the puzzle is the shift itself.