Skip to Content
Binal

binal

Declarative binary modeling for Python.

Describe a binary format once, as a Python class or as a .binal schema. Encoding, decoding, validation, checksums, layout, and error messages all come from that one description.

from dataclasses import field
from typing import Annotated

from binal import CRC32, BinaryModel, Checksum, LengthOf, Sized, UInt8, UInt16, UInt32


class Frame(BinaryModel, byte_order="big"):
    version: UInt8
    length: Annotated[UInt16, LengthOf("payload")] = field(init=False)
    payload: Annotated[bytes, Sized("length")]
    crc: Annotated[UInt32, Checksum(CRC32, fields=("version", "length", "payload"))] = (
        field(init=False)
    )


data = Frame(version=1, payload=b"Hello").encode()  # length and CRC are computed
frame = Frame.decode(data)  # and verified
frame.payload  # b'Hello'

Start with the quick start, or go straight to what your format needs.

Describe a format

Your format hasUse
Integers of any width, varintsUInt8 to UInt128, Integer(12), ULEB128, ZigZag, VLQ
Floats, fixed point, decimals, BCDFloat16 to Float128, BFloat16, FixedPoint, Decimal64DPD, BCD
Text and bytesSized, Padded, Prefixed, NullTerminated, Terminated, Greedy
UUIDs, addresses, dates and timesUUID, GUID, IPv4, MAC, Timestamp, Duration
Flags and packed bitsBitModel, Bits, enums and flags, fixed storage widths
Lists and tuplesFixed, counted, prefixed, terminated, greedy, and byte-bounded
Lengths, counts, and sizes that depend on other fieldsLengthOf, CountOf, Sized("length"), or a Python callable
Optional parts and message typesWhen, TaggedUnion, untagged unions
Magic numbers, versions, padding, alignmentConst, Padding, Align
ChecksumsCRC-8 to CRC-64, Adler-32, or any function
Pointers, shared objects, cyclesRef, Offset
Compressed or scattered dataSpace("zlib"), Space(gather=...)
Values that are not in the dataContext, Args
Something elseA codec of your own

Use it

ToUse
Decode bytes, files, streams, or asyncio streamsI/O
Parse data that arrives in piecesincremental_parser
Read one record of a large fileBinaryReader.read_at
Process many records in one calldecode_many, encode_many
Reject invalid data with a useful messageValidation
Bound memory and depth for untrusted inputLimits
Edit a file and keep every byte you did not touchDocuments
See where each field is, or why data does not decodeInspection
Know sizes and offsets without any dataschema() and layout()
Write a format as text, without Python classesThe schema language
Use a model’s format from other languagesPortable schemas

The repository’s examples/ are complete programs: Modbus RTU, TCP segments, a telemetry receiver, a map tile archive, and editing a PNG’s metadata.