Bitwise integers

Contents

Bitwise integers#

Python int is arbitrary precision and supports the standard bit operations. The operator’s storage for compact flag sets, bitmaps over a fixed namespace, and ad-hoc bitwise extraction.

flags = 0
flags |= 0b0001               # set bit 0
flags &= ~0b0010              # clear bit 1
bit_set = (flags >> 2) & 1    # test bit 2
flags ^= 0b1000               # toggle bit 3

Named constants make the intent legible.

READ, WRITE, EXEC = 1 << 0, 1 << 1, 1 << 2
perms = READ | WRITE
if perms & EXEC:
    ...

For dense bit storage at scale, int is fast and uses no fixed width; for typed fixed-width fields on the wire, see struct.

The standard library has helpers for population count and bit length.

x = 0b10110101
x.bit_count()                 # 5  (popcount)
x.bit_length()                # 8
x.to_bytes(4, "big")          # b'\x00\x00\x00\xb5'
int.from_bytes(b"\xff\x00", "big")  # 65280

References#