Skip to Content
Binal
Binary Types

Integers

Signed and unsigned integers

TypePython typeSize
UInt8, Int8int1 byte
UInt16, Int16int2 bytes
UInt24, Int24int3 bytes
UInt32, Int32int4 bytes
UInt64, Int64int8 bytes
Float16, Float32, Float64float2 / 4 / 8 bytes
Bool8bool1 byte

Custom widths are available with Integer(bits, signed=False).

Variable-length integers

ULEB128, SLEB128, VarUInt, VarInt, ZigZag32, ZigZag64.

ZigZag32 and ZigZag64 are genuinely distinct widths, not aliases: ZigZag32 zigzag-encodes a 32-bit signed value (range -2**31 .. 2**31-1, at most 5 bytes on the wire) and ZigZag64 a 64-bit signed value (range -2**63 .. 2**63-1, at most 10 bytes). A value outside the width’s range raises ValidationError at construction and at encode.

Plain ULEB128 / SLEB128 (and VarUInt / VarInt) 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 BinaryModel, ULEB128, ZigZag32, ZigZag64


class Small(BinaryModel, byte_order="big"):
    v: ZigZag32


class Large(BinaryModel, byte_order="big"):
    v: ZigZag64


class AnySize(BinaryModel, byte_order="big"):
    v: ULEB128


Small(v=-1).encode()  # b'\x01'
Large(v=2**31).encode()  # fits: ZigZag64 covers the int64 range
Small(v=2**31)  # ValidationError: outside the int32 range
AnySize(v=2**100).encode()  # arbitrary precision
Small.decode(b"\x81\x00")  # b'\x81\x00' is an overlong encoding of -1: accepted