construct Binary Data Parser

2.10.70 · active · verified Thu Apr 09

construct is a powerful declarative symmetric parser/builder for binary data, supporting Python 3.6+. It allows you to define the structure of binary data using Python objects and then parse or build data according to that structure. The current version is 2.10.70, and it maintains a fairly active release cadence, often releasing minor fixes and improvements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a `Struct` using various constructors like `Bytes`, `Int8ub`, `Array`, and `GreedyRange`. It shows how to use lambda functions within a structure definition to refer to previously parsed fields (e.g., `ctx.count`). Finally, it illustrates building Python objects into binary data and parsing binary data back into Python objects, including basic error handling.

from construct import Struct, Int8ub, Bytes, Array, GreedyRange, StreamError

# Define a simple binary structure
# A header, an array of 8-bit unsigned integers, and a variable-length data block
packet_struct = Struct(
    "header" / Bytes(4), # 4-byte header
    "count" / Int8ub,    # 1-byte count of following integers
    "data" / Array(lambda ctx: ctx.count, Int8ub), # Array of 'count' integers
    "payload" / GreedyRange(Int8ub) # Remaining bytes as a list of integers
)

# Example data to build
my_data = {
    "header": b"\xde\xad\xbe\xef",
    "count": 3,
    "data": [10, 20, 30],
    "payload": [1, 2, 3, 4, 5]
}

# Build binary data from Python object
built_binary = packet_struct.build(my_data)
print(f"Built binary: {built_binary.hex()}")

# Parse binary data into Python object
# Using a different example binary for parsing
binary_to_parse = b"\xaa\xbb\xcc\xdd\x02\x01\x02\xff\xee\xdd"

try:
    parsed_object = packet_struct.parse(binary_to_parse)
    print(f"Parsed object: {parsed_object}")

    # Accessing fields
    print(f"Parsed header: {parsed_object.header.hex()}")
    print(f"Parsed data: {parsed_object.data}")
except StreamError as e:
    print(f"Error parsing data: {e}")

view raw JSON →