Bit Fields
Bit models and bit fields
from typing import Annotated
from binal import BitModel, Bits
class PacketFlags(BitModel, bit_order="msb"):
version: Annotated[int, Bits(3)]
encrypted: Annotated[bool, Bits(1)]
priority: Annotated[int, Bits(4)]
PacketFlags(version=3, encrypted=True, priority=7).encode() # b'\x77' Bit order is msb (most-significant-bit first) or lsb. int bit fields are unsigned by default; pass signed=True for a two’s-complement field, which sign-extends on decode. Bit arrays pack elements across byte boundaries.
Storage width
A bit model is parameterised by its storage width with storage=: the fields pack into one integer of that width, serialized with the storage byte order. The sum of the fields’ bit widths must equal the storage width, or class definition fails with SchemaError. Trailing padding bits are never implicit: name them explicitly, for example a Const(0) bit field, which writes zero on encode and verifies zero on decode.
from dataclasses import field
from enum import IntEnum
from typing import Annotated
from binal import BitModel, Bits, Bool1, Const, UInt16
class Opcode(IntEnum):
QUERY = 0
STATUS = 2
NOTIFY = 4
UPDATE = 5
class DnsFlags(BitModel, storage=UInt16, byte_order="big", bit_order="msb"):
response: Bool1
opcode: Annotated[Opcode, Bits(4)]
authoritative: Bool1
truncated: Bool1
recursion_desired: Bool1
recursion_available: Bool1
reserved: Annotated[int, Bits(3), Const(0)] = field(init=False)
rcode: Annotated[int, Bits(4)]
flags = DnsFlags.decode(b"\x81\x80") # the flags of a typical DNS response
flags.response, flags.opcode, flags.recursion_available
# (True, <Opcode.QUERY: 0>, True)
flags.encode() # b'\x81\x80' A BitModel without storage keeps the open-ended packing: its fields pack contiguously and the encoding is padded to a whole number of bytes.
Enum and flag bit fields
An enum or flag on a Bits field is a field of exactly that width, carrying the enum: it converts via the enum on decode and via int(value.value) on encode. on_unknown controls decoding of values not in the enum, as with EnumField: "raise" (default) raises a decode error, "keep" keeps the raw integer value.
from enum import IntFlag
from typing import Annotated
from binal import BitModel, Bits
class Access(IntFlag):
EXECUTE = 1
WRITE = 2
READ = 4
class UnixMode(BitModel, bit_order="msb"):
kind: Annotated[int, Bits(4)]
special: Annotated[int, Bits(3)]
owner: Annotated[Access, Bits(3)]
group: Annotated[Access, Bits(3)]
other: Annotated[Access, Bits(3)]
UnixMode.decode(bytes.fromhex("81a4")).owner # <Access.WRITE|READ: 6>: 0o100644 Nested order precedence
A nested model’s own class-level byte_order / bit_order win over its parent’s, and a field-level ByteOrder marker on the field that holds the nested model wins over both. A model encodes identically standalone and nested under equivalent configuration. A nested BitModel with a fixed storage width is byte-aligned on exit; one without storage ends at its bit position and the parent continues packing (when the bit orders agree).
Bit-accurate layout
schema() reports bit_offset / bit_size per field, and layout() reports the logical bit count in total_bits next to total_bytes. The static size simulation mirrors the writer exactly, so schema offsets, layout offsets, and fixed_size() agree with len(encode()) for bit fields, non-byte-multiple integers, and nested bit models.
Bits, booleans, and masks
Bit is a one-bit unsigned integer and Bool1 a one-bit boolean (Annotated[int, Bits(1)] and Annotated[bool, Bits(1)]). Bits(width, signed=True) is a two’s complement bit field. A bit sequence is a list of Bool1 with a count, and a bit mask is an enum.Flag (or IntFlag) on a Bits or integer field.
from enum import Flag
from typing import Annotated
from binal import Array, BitModel, Bits, Bool1
class Alarm(Flag):
OVERVOLTAGE = 4
OVERCURRENT = 2
OVERHEAT = 1
class MotorStatus(BitModel):
running: Bool1
alarms: Annotated[Alarm, Bits(3)]
trim: Annotated[int, Bits(4, signed=True)]
inputs: Annotated[list[Bool1], Array(8)]
MotorStatus(
running=True,
alarms=Alarm.OVERVOLTAGE | Alarm.OVERHEAT,
trim=-3,
inputs=[True, False] * 4,
).encode() # b'\xdd\xaa'