Masks, Flags & Packed Fields
In short: a mask is a number whose bits mark the positions you care about. x | (1<<k)
sets bit k, x & ~(1<<k) clears it, x ^ (1<<k) toggles it, and (x>>k) & 1 tests it.
Shift a mask of w ones, (1<<w) - 1, to cover any run of bits and you can pack several
fields side by side in one word: shift a value up by its field's position to pack it,
shift and mask to unpack it. A field that's too wide for its lane spills silently into
the lane next door, so a packer has to check widths, not just trust them.

Lesson 1 packed a Quarry record header into one 32-bit word with a line that looked like
magic: (3071 << 20) | (17 << 14) | (2 << 11) | 1500. This lesson takes that line
apart. It covers the four things you do to a single bit, then masks, the patterns
of 1s that pick out several bits at once. Then it packs whole fields side by side in
one word. Most binary formats you'll meet work this way: file headers, network
packets, pixel formats, CPU instructions and database pages.
One bit at a time: set, clear, toggle, test
Build a word with a single 1 at position k with 1 << k, and combine it with the
three operators from lesson 1:
| To… | Write | Why it works |
|---|---|---|
| set bit k | x | (1 << k) |
OR with 1 forces a 1, OR with 0 changes nothing |
| clear bit k | x & ~(1 << k) |
the mask is all 1s except at k, and AND with 0 forces a 0 |
| toggle bit k | x ^ (1 << k) |
XOR with 1 flips, XOR with 0 keeps |
| test bit k | (x >> k) & 1 |
slide bit k down to position 0 and keep only it |
Quarry's status word gives each flag a name, so no one has to remember which bit is which:
~DIRTY is negative in Python, because it has infinitely many 1s on the left. That's
exactly what you want in a clear mask: every bit except bit 0 survives the AND, however
wide status is.
❓ Cross-question — "Isn't there a library for this?" Yes.
enum.IntFlaggives named flags that combine with|and print readably. Use it in application code. The operators underneath are the same ones shown here, and a storage engine that packs millions of headers uses them directly.