Back
+30 XP
Concept

Bit-Packed Status Bitmask (64 flags in 8 bytes)

Storing 64 individual booleans in Python dictionaries consumes over 1,500 bytes of heap memory. A bitmask packs 64 boolean flags into an 8-byte unsigned integer (uint64) using bitwise shifts and masks, delivering microsecond operations with zero memory waste.

python
# Set bit N:
mask |= (1 << n)
# Clear bit N:
mask &= ~(1 << n)
# Test bit N:
is_set = bool(mask & (1 << n))

# Bit-Packed Status Bitmask (64 flags in 8 bytes) In Python, a single boolean object (`True` or `False`) occupies 28 bytes of heap memory. Storing a dictionary of 64 feature flags (`{"can_read": True, ...}`) burns over 1,500 bytes of memory and requires hash lookups for every check. ⚡🛡️ Low-level systems engineers pack all 64 boolean flags into a single 64-bit integer (`uint64`), consuming exactly **8 bytes** total. - **Set flag $n$**: `mask |= (1 << n)` - **Clear flag $n$**: `mask &= ~(1 << n)` - **Test flag $n$**: `bool(mask & (1 << n))` - **Toggle flag $n$**: `mask ^= (1 << n)` ```python import struct # Convert 64-bit int to 8 binary bytes raw = struct.pack(">Q", mask) # Unpack back to int mask, = struct.unpack(">Q", raw) ``` ## Pop Quiz Why do low-level storage engines use bitmasks rather than lists of boolean flags? - [ ] Bitmasks collapse multiple flags into a single CPU register with zero pointer overhead and O(1) bitwise operations. - [ ] Python booleans cannot be serialized across network sockets without base64 encoding. - [ ] Hardware disk controllers automatically invert boolean arrays during write operations. - [ ] Bitmasks bypass operating system filesystem permissions checks. ## Real-World Challenge Implement `Bitmask64`. It must expose: - `set_flag(index: int, value: bool)`: Updates bit $0 \le \text{index} < 64$. - `get_flag(index: int) -> bool`: Returns current boolean state. - `to_bytes() -> bytes`: Serializes the bitmask into an 8-byte big-endian unsigned integer (`>Q`). - `from_bytes(data: bytes)`: Reconstructs a `Bitmask64` instance from an 8-byte buffer. <details> <summary>Solution</summary> ```python import struct class Bitmask64: def __init__(self, initial_value: int = 0): self._mask = initial_value & 0xFFFFFFFFFFFFFFFF def set_flag(self, index: int, value: bool): if not (0 <= index < 64): raise IndexError(f"Bit index {index} out of bounds (0..63)") if value: self._mask |= (1 << index) else: self._mask &= ~(1 << index) def get_flag(self, index: int) -> bool: if not (0 <= index < 64): raise IndexError(f"Bit index {index} out of bounds (0..63)") return bool(self._mask & (1 << index)) def to_bytes(self) -> bytes: return struct.pack(">Q", self._mask) @classmethod def from_bytes(cls, data: bytes) -> "Bitmask64": if len(data) != 8: raise ValueError(f"Expected exactly 8 bytes, got {len(data)}") val, = struct.unpack(">Q", data) return cls(val) # Verification bm = Bitmask64() bm.set_flag(0, True) # LSB bm.set_flag(7, True) bm.set_flag(63, True) # MSB assert bm.get_flag(0) is True assert bm.get_flag(1) is False assert bm.get_flag(7) is True assert bm.get_flag(63) is True raw_bytes = bm.to_bytes() assert len(raw_bytes) == 8 reconstructed = Bitmask64.from_bytes(raw_bytes) assert reconstructed.get_flag(0) is True assert reconstructed.get_flag(1) is False assert reconstructed.get_flag(63) is True ``` </details>