Skip to main content

binal

Declarative binary modeling for Python

Define a binary format once, as a Python class, and get encoding,
decoding, validation, and layout from the same declaration.

PyPI version Python 3.13+ License: MIT

Documentation · Capabilities · Installation · Usage · Contributing


Capabilities

Area What it covers
Binary types Integers of any width up to 128 bits, varints (LEB128, zigzag, VLQ), binary floats from 8-bit to binary128, decimal floats (BID and DPD), fixed point, BCD, bytes, and strings (sized, prefixed, terminated, greedy)
Semantic types UUIDs, IP and MAC addresses, timestamps, dates, times, durations, complex and rational numbers
Modeling Nested and recursive models, bit fields, lists, tuples, enums and flags, tagged and untagged unions, conditional and dependent fields, derived lengths and counts
References Offsets and pointers into address spaces, shared and cyclic objects
Checksums CRC-8, CRC-16, CRC-32, CRC-32C, CRC-64, and Adler-32, verified on decode
I/O File, buffer, stream, and asynchronous I/O, incremental parsing and partial decoding, sequences of records in one call
Validation Field constraints, cross-field validation, and structured errors with field paths and byte offsets
Introspection Static schema and runtime layout with field offsets and sizes
Formats and documents .binal schemas run from Python, lossless editing that keeps unknown bytes, and skeleton schemas of common file formats
Portable schemas A model's format exported as JSON for other languages and tools
Low-level I/O BinaryReader and BinaryWriter for ad-hoc formats and custom codecs

Installation

binal supports Python 3.13 and newer. It depends on fastcrc (CRC checksums) and tibs (bfloat16 and 8-bit floats), both with prebuilt wheels.

Add it to a uv project:

uv add binal

To install it in an active Python environment:

pip install binal

To build from source, which needs Rust 1.88 or newer:

git clone https://github.com/nolantw/binal
cd binal
uv sync --locked

Usage

Describe a format once

Lengths, checksums, bit fields, constants, and unions are declared, not coded. Derived fields take no argument: encoding computes them and decoding verifies them.

from dataclasses import field
from enum import IntEnum
from typing import Annotated

from binal import (
    CRC32,
    BinaryModel,
    BitModel,
    Bits,
    Checksum,
    Const,
    LengthOf,
    Prefixed,
    Range,
    Sized,
    TaggedUnion,
    UInt8,
    UInt16,
    UInt32,
)


class Kind(IntEnum):
    TEXT = 1
    MOVE = 2


class Flags(BitModel):
    urgent: Annotated[bool, Bits(1)]
    priority: Annotated[int, Bits(7)]


class Text(BinaryModel, byte_order="big"):
    body: Annotated[str, Prefixed(UInt16)]


class Move(BinaryModel, byte_order="big"):
    x: Annotated[UInt16, Range(0, 639)]
    y: Annotated[UInt16, Range(0, 479)]


class Message(BinaryModel, byte_order="big"):
    magic: Annotated[bytes, Const(b"MSG")] = field(init=False)
    flags: Flags
    kind: Annotated[Kind, UInt8]
    body: Annotated[
        Text | Move, TaggedUnion("kind", {Kind.TEXT: Text, Kind.MOVE: Move})
    ]
    crc: Annotated[UInt32, Checksum(CRC32, fields=("flags", "kind", "body"))] = field(
        init=False
    )


message = Message(Flags(urgent=True, priority=5), Kind.TEXT, Text("Hello"))
data = message.encode()
data.hex(" ")  # '4d 53 47 85 01 00 05 48 65 6c 6c 6f 67 5f be 1c'
assert Message.decode(data) == message

See exactly what went wrong

Errors name the field, the byte, and the rule.

from binal import DecodeError, ValidationError

try:
    Message.decode(data[:9])
except DecodeError as error:
    print(error.path, error.offset, error.is_incomplete)
    # Message.body.body 7 True

try:
    Move(640, 0)
except ValidationError as error:
    print(error.path, error.expected, error.received)
    # Move.x value between 0 and 639 640

Follow pointers, even in cycles

A Ref field stores an address; its value is the object there. Encoding places the objects and fills in the addresses.

from binal import Ref


class Node(BinaryModel):
    value: UInt8
    next: Annotated["Node | None", Ref(UInt8, null=0)]


Node(1, Node(2, None)).encode()  # b"\x01\x02\x02\x00"

# A document keeps references, so a cycle can be read and edited.
document = Node.open(b"\x01\x02\x02\x00")
second = document.root.next
document[second] = Node(7, None)
document.encode()  # b"\x01\x02\x07\x00"

Edit a file

A .binal schema describes a format as text. Here a PNG's title changes, and its length and CRC follow.

from pathlib import Path

from binal import Format

png = Format.load("formats/png.binal")
image = png.decode("Png", Path("formats/fixtures/image.png").read_bytes())
for chunk in image["chunks"]:
    if chunk["type"] == b"tEXt" and chunk["data"]["keyword"] == "Title":
        chunk["data"]["text"] = "Edited with binal"
        del chunk["length"], chunk["crc"]
edited = png.encode("Png", image)

The schemas in formats/ are skeletons, not parsers for their formats: most describe headers and pointers, checked on small fixtures, and leave the harder tables as bytes. See what each one leaves out.

Read it any way it arrives

from io import BytesIO

stream = BytesIO(data * 3)
assert list(Message.iter_read(stream)) == [message] * 3  # one at a time
assert Message.decode_many(data * 3) == [message] * 3  # in one call
record, consumed = Message.decode_partial(data + b"more")  # a prefix

Take the format to other languages

from binal import export_schema

export_schema(Move).to_source()
# struct Move {
#     byte_order big,
#     bit_order msb,
#     x: u16 where x >= 0 && x <= 639,
#     y: u16 where y >= 0 && y <= 479,
# }

Project status

binal is pre-1.0: the API may change between minor releases.

License

MIT. See LICENSE.

Metadata

Release files for binal 0.6.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for binal 0.6.2
File Size Uploaded Provenance Actions
binal-0.6.2.tar.gz 264.4 kB With provenance Details for binal-0.6.2.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for binal 0.6.2
File Actions
binal-0.6.2-cp313-abi3-win_amd64.whl CPython 3.13 abi3 Windows x86-64 Details for binal-0.6.2-cp313-abi3-win_amd64.whl
binal-0.6.2-cp313-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl CPython 3.13 abi3 Linux glibc 2.17+ x86-64 Details for binal-0.6.2-cp313-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
binal-0.6.2-cp313-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl CPython 3.13 abi3 Linux glibc 2.17+ ARM64 Details for binal-0.6.2-cp313-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
binal-0.6.2-cp313-abi3-macosx_11_0_arm64.whl CPython 3.13 abi3 macOS 11.0+ ARM64 Details for binal-0.6.2-cp313-abi3-macosx_11_0_arm64.whl
binal-0.6.2-cp313-abi3-macosx_10_12_x86_64.whl CPython 3.13 abi3 macOS 10.12+ x86-64 Details for binal-0.6.2-cp313-abi3-macosx_10_12_x86_64.whl

Total release size: 5.5 MB

Release files / binal-0.6.2.tar.gz

Download URL binal-0.6.2.tar.gz
Size 264.4 kB
Tags Source
SHA-256 checksum
How to use checksums
23b009b69c937eb51d167fa3e7e0ef2e7b73188ca9ed30624e71360431a1936d
BLAKE2b-256 checksum
How to use checksums
43da704239d5a55769858696e24535b3ddbc4a02f7b227fb6719aef416e282e3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Release files / binal-0.6.2-cp313-abi3-win_amd64.whl

Download URL binal-0.6.2-cp313-abi3-win_amd64.whl
Size 976.8 kB
Tags CPython 3.13 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
fae95a50b79a854d19ad66a013df1a4631f768d291b16323daba5fc901d39609
BLAKE2b-256 checksum
How to use checksums
670b24bd0e27d6f3f58a5665207405f71c21bceee0115ab458e00f0a3c982cb6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Release files / binal-0.6.2-cp313-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

Download URL binal-0.6.2-cp313-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 1.1 MB
Tags CPython 3.13 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
01feb009cab8183e178d7bf5b7baca4f008cf469915e1b9aebbd0298bc9c7cf3
BLAKE2b-256 checksum
How to use checksums
f2923963f701a6cd316e515f8c277186112e36e3d5a1b8ead5780dcf7d87e10c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Release files / binal-0.6.2-cp313-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl

Download URL binal-0.6.2-cp313-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
Size 1.1 MB
Tags CPython 3.13 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
e35b702adc625cc9ba594ea9f0b40b2dad7c696af4c92fc3eec5b1502585e1bc
BLAKE2b-256 checksum
How to use checksums
d54ba6a93e251769bc0c33839df71efa105bb9b60c599b40741d0cc295e3944c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Release files / binal-0.6.2-cp313-abi3-macosx_11_0_arm64.whl

Download URL binal-0.6.2-cp313-abi3-macosx_11_0_arm64.whl
Size 1.0 MB
Tags CPython 3.13 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
e50c7d3d02a14ccf9a2b0ee49cfba58fa5f9d8e9811539bbff898ba5ae6ef8ca
BLAKE2b-256 checksum
How to use checksums
17a1c1c24e45e7dc4c7a901af61ec85a3722a8c3d04ff8326dea2956a70f2ffd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Release files / binal-0.6.2-cp313-abi3-macosx_10_12_x86_64.whl

Download URL binal-0.6.2-cp313-abi3-macosx_10_12_x86_64.whl
Size 1.1 MB
Tags CPython 3.13 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
d7d94c29f867d18aa5bdcc78aa3032b2524abc00497170e754aa07b72a4d138b
BLAKE2b-256 checksum
How to use checksums
7b786c1a4b80c1805be78f9c7f28a5f0788453e978a57b8ff14389ee8902d5bd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Security for binal 0.6.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 6 files in this release have been uploaded with provenance metadata.

Select from 6 files

Attestation for binal-0.6.2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page