Numbers and bits · 3 / 15 Theory

Bit masks and flags

An integer can store many yes/no flags at once: bit i tells whether flag i is on. It is the usual way to represent permissions, options and small subsets.

READ, WRITE, EXECUTE = 1 << 0, 1 << 1, 1 << 2   # 1, 2, 4

permissions = READ | WRITE          # turn several flags on at once
print(permissions)                      # 3
print(bool(permissions & WRITE))     # True
print(bool(permissions & EXECUTE))     # False

permissions |= EXECUTE                 # turn on
permissions &= ~WRITE                # turn off
permissions ^= READ                     # flip
print(permissions)                      # 4

# Subsets of {a, b, c}: each 3-bit mask is a subset
letters = "abc"
for m in range(1 << 3):
    print(m, "".join(letters[i] for i in range(3) if m >> i & 1) or "-")
# 0 -   1 a   2 b   3 ab   4 c   5 ac   6 bc   7 abc (one line each)
  • Turn on: m |= 1 << i. Turn off: m &= ~(1 << i). Flip: m ^= 1 << i. Query: m >> i & 1.
  • A mask of n bits represents a subset of n elements: walking range(1 << n) visits all the subsets.
  • Named constants (READ, WRITE…) make the code readable; for long lists the enum module offers IntFlag.
  • Everything fits in a single integer, which saves memory and lets you compare or combine sets with a single operation.

You practice it in Bit mask commands and Gray code.