Integers
Fixed-width, arbitrary-width, and variable-length integers
| Type | Python type | Size |
|---|---|---|
UInt8, Int8 | int | 1 byte |
UInt16, Int16 | int | 2 bytes |
UInt24, Int24 | int | 3 bytes |
UInt32, Int32 | int | 4 bytes |
UInt48, Int48 | int | 6 bytes |
UInt64, Int64 | int | 8 bytes |
UInt128, Int128 | int | 16 bytes |
Bool8 | bool | 1 byte |
Any other width uses Integer metadata: Annotated[int, Integer(12, signed=True)]. A width that is not a whole number of bytes is bit-packed. Integer(bits, signed=False, byte_order=None) takes an optional byte order that overrides the model’s for that field.
Bit fields, single-bit booleans (Bit, Bool1), and bit masks are on the Bit Fields page.
Variable-length integers
| Type | Encoding |
|---|---|
ULEB128 | Unsigned LEB128: 7 bits per byte, least significant group first |
SLEB128 | Signed LEB128 (two’s complement) |
ZigZag32 | Zigzag, then ULEB128; bounded to the int32 range (at most 5 bytes) |
ZigZag64 | Zigzag, then ULEB128; bounded to the int64 range (at most 10 bytes) |
ZigZag | Zigzag, then ULEB128; arbitrary precision |
VLQ | Unsigned, most significant group first (MIDI variable-length quantity) |
Each is an alias of the VarInt(kind, zigzag=False, bits=None) marker. kind is "uleb128", "sleb128", or "vlq"; zigzag=True maps signed values to unsigned ones (0, -1, 1, -2 to 0, 1, 2, 3) and applies to "uleb128" and "vlq"; bits bounds a zigzag value to that two’s complement width, so VarInt("vlq", zigzag=True, bits=16) is a zigzag VLQ over the int16 range. A value outside a bounded range raises ValidationError at construction and at encode.
Unbounded varints are arbitrary precision: they round-trip values of any size and are bounded only by the configured varint byte limit (Limits.max_varint_bytes, default 1024).
Non-canonical (overlong) varint encodings are accepted on decode — a value encoded with more bytes than the minimum still decodes to the same value. Only the length cap is enforced. This follows the protobuf convention: canonicality is not part of the wire format, so binal does not reject overlong encodings.
from binal import VLQ, BinaryModel, ULEB128, ZigZag, ZigZag32
class Small(BinaryModel, byte_order="big"):
v: ZigZag32
class AnySize(BinaryModel, byte_order="big"):
v: ULEB128
class Signed(BinaryModel, byte_order="big"):
v: ZigZag
class Midi(BinaryModel, byte_order="big"):
delta: VLQ
Small(v=-1).encode() # b'\x01'
Small(v=2**31) # ValidationError: outside the int32 range
AnySize(v=2**100).encode() # arbitrary precision
Signed(v=-(2**100)).encode() # arbitrary-precision zigzag
Midi(delta=0x80).encode() # b'\x81\x00'
Small.decode(b"\x81\x00") # an overlong encoding of -1: accepted