Skip to Content
Binal
API Reference

Checksums

CRC32, CRC16, Adler32, and the Checksum marker

Checksum(algorithm, fields=(...)) marks an integer field as a checksum over the encoded bytes of the named fields. The checksum is computed on encode (after offsets are patched, so a checksum covering an offset field digests the final bytes) and verified on decode; a mismatch raises DecodeError. The checksum field is derived — it takes no constructor argument and is stored as 0 until encoded. A checksum must cover earlier fields, and cannot cover another checksum or a conditional field (unless the checksum shares the field’s exact When condition).

Three algorithms are built in, as plain functions from bytes to int:

  • CRC32 — CRC-32 (IEEE), a 32-bit value (UInt32 field).
  • CRC16 — CRC-16/CCITT-FALSE, a 16-bit value (UInt16 field).
  • Adler32 — Adler-32, a 32-bit value (UInt32 field).

Any callable taking bytes and returning an int can be used as the algorithm (ChecksumAlgorithm).

from typing import Annotated

from binal import (
    Adler32,
    BinaryModel,
    Checksum,
    CRC16,
    CRC32,
    Prefixed,
    UInt16,
    UInt32,
)


class Packet(BinaryModel, byte_order="big"):
    body: Annotated[bytes, Prefixed(UInt16)]
    crc: Annotated[UInt32, Checksum(CRC32, fields=("body",))]


class Frame(BinaryModel, byte_order="big"):
    body: Annotated[bytes, Prefixed(UInt16)]
    crc: Annotated[UInt16, Checksum(CRC16, fields=("body",))]
    adler: Annotated[UInt32, Checksum(Adler32, fields=("body",))]


packet = Packet(body=b"hello")
Packet.decode(packet.encode()) == packet  # True

# Corrupt one byte of the body: decode raises DecodeError.
corrupt = bytearray(packet.encode())
corrupt[3] ^= 0xFF
Packet.decode(bytes(corrupt))  # DecodeError: checksum mismatch

The checksum is computed over the encoded bytes of the listed fields, concatenated in the order listed — not over the whole record, and not over the Python values. For a checksum over a bit field, the digest covers the byte(s) the bits occupy.