Logic and bit operations

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
x
0001
1 << 2
0100
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:

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.