Python's struct Module: Packing Values into Binary Records

This article explains how the struct module packs Python values into binary records, how prefixes control byte order and alignment, and which errors a wrong layout produces.

A bright green snake packed into tight, regular coils on a dark branch against a black background
Photo by Mykhailo Amirdzhanian on Unsplash

Files, network protocols and C libraries exchange data as sequences of bytes with a fixed layout, in which every field occupies a known number of bytes at a known position. The present article examines the module struct, which converts Python values into such byte sequences and back according to a format string that describes the layout. It explains how packing and unpacking work, how the prefix of the format string controls byte order, size and alignment, how a binary file header is parsed, how a compiled Struct object reads and writes records inside an existing buffer, and which errors appear when the layout is misunderstood. Describing a binary record in one short string, instead of shifting and masking individual bytes, is the secret weapon of this module.

Packing and Unpacking with a Format String

The function struct.pack receives a format string and a series of values and returns a bytes object; struct.unpack receives the same format string and the bytes, and returns a tuple of values. Each character of the format string describes one field: i is a C int, f a C float of four bytes, d a double of eight, c a single byte, ? a boolean, H an unsigned short of two bytes, and s preceded by a number is a byte string of that length.

import json
import struct

record = struct.pack("ifc", 101, 1.5, b"A")
print(record)                        # Output: b'e\x00\x00\x00\x00\x00\xc0?A'
print(struct.unpack("ifc", record))  # Output: (101, 1.5, b'A')
print(struct.calcsize("ifc") == len(record))  # Output: True

as_json = json.dumps({"id": 101, "ratio": 1.5, "rank": "A"}).encode()
print(len(record) < len(as_json))    # Output: True

The integer 101 appears as the byte e, whose code is 101, followed by three zero bytes, and the float 1.5 occupies the next four bytes. The function calcsize returns the number of bytes that a format requires, which here is 9, and the same three values serialized as JSON take 35 bytes in the measurement of this article. Unpacking always returns a tuple, even for a single field, and requires the same format string that was used for packing, because the bytes themselves carry no description of their layout.

Byte Order, Size and Alignment

The first character of a format string may be a prefix that fixes three properties of the layout: the order of the bytes of each number, the size of each type and the alignment of the fields. With @, which is assumed when no prefix is given, all three follow the native conventions of the C compiler of the current machine. With =, <, > or !, sizes are standard and no alignment is added; < selects little-endian order, in which the least significant byte comes first, and > or ! select big-endian order, the network byte order of internet protocols.

import struct

number = 0x1234
print(struct.pack(">H", number).hex())  # Output: 1234
print(struct.pack("<H", number).hex())  # Output: 3412

print(struct.calcsize("<icf"))          # Output: 9
print(struct.calcsize("@icf") > struct.calcsize("<icf"))  # Output: True
print(struct.calcsize("@ifc") == struct.calcsize("<ifc"))  # Output: True

The same number produces the bytes 12 34 in big-endian order and 34 12 in little-endian order. The layout icf takes 9 bytes in standard mode, but 12 bytes in native mode on the machine of the test, because the compiler places a float at an address divisible by four and therefore inserts three bytes of padding after the single character. The order ifc needs no padding between its fields, so both modes give 9 bytes. Native mode reproduces the layout of a C structure, the same layout that ctypes.Structure follows, as described in the article devoted to ctypes; a file format or a protocol, which must read the same on every machine, requires an explicit prefix.

Save File Format: Reading a Binary Header

A binary file usually begins with a header of fixed size that identifies the format and locates the rest of the data. The header of a BMP image occupies 14 bytes in little-endian order: two signature bytes, BM, the size of the file as an unsigned 32-bit integer, two reserved 16-bit fields and the offset at which the pixel data begin.

import struct

BMP_HEADER = struct.Struct("<2sIHHI")

header = BMP_HEADER.pack(b"BM", 15000, 0, 0, 54)
print(BMP_HEADER.size)        # Output: 14
print(header[2:6].hex())      # Output: 983a0000

signature, file_size, _, _, data_offset = BMP_HEADER.unpack(header)
print(signature, file_size, data_offset)  # Output: b'BM' 15000 54

data = header + bytes(100)    # header followed by other content
print(BMP_HEADER.unpack_from(data, 0)[1])  # Output: 15000

The format string documents the header field by field, and building the example with pack guarantees that the bytes correspond to the values: the size 15000 is written as 98 3a 00 00, least significant byte first. A hand-typed literal is a frequent source of error: the bytes d8 38 00 00, which differ by only two hexadecimal digits, encode 14552 instead of 15000. The method unpack_from reads the header from a larger buffer, starting at an offset, without the slicing that unpack would need, since unpack requires a buffer whose length equals the size of the format exactly.

Reusing a Layout: Struct, pack_into and iter_unpack

A Struct object compiles its format string once, which the documentation describes as more efficient than calling the module functions repeatedly with the same format, although the module also caches recently used formats. The object offers the same operations as the module, together with pack_into, which writes into an existing writable buffer, and iter_unpack, which reads a sequence of records of equal size.

import struct

POINT = struct.Struct("<hhf")   # x, y and a weight
points = [(1, 2, 0.5), (-3, 4, 1.25), (5, -6, 2.0)]

buffer = bytearray(POINT.size * len(points))
for index, point in enumerate(points):
    POINT.pack_into(buffer, index * POINT.size, *point)

print(len(buffer))                           # Output: 24
print(list(POINT.iter_unpack(buffer)) == points)  # Output: True

view = memoryview(buffer)
print(POINT.unpack_from(view, POINT.size))   # Output: (-3, 4, 1.25)

The three records are written into a single preallocated bytearray without creating intermediate bytes objects, and iter_unpack recovers them in order, provided that the length of the buffer is a multiple of the record size. Both functions accept any object that supports the buffer protocol, including a memoryview, which allows a large binary file to be read once and parsed in place, as examined in the article devoted to memoryview. Python 3.14 adds the formats F and D, which pack complex numbers as two floats or two doubles.

Pitfalls of struct

Every mistake in a format string produces bytes that are valid but mean something else, so errors tend to appear far from their cause. Six pitfalls are distinguished, which are the following:

  1. Forgetting the prefix. Without a prefix, the layout uses native sizes and alignment, which may differ between machines and insert padding bytes.
  2. Wrong byte order. Little-endian data read as big-endian produce valid but meaningless numbers, with no error.
  3. Out-of-range values. An integer that does not fit its format raises struct.error instead of wrapping around.
  4. Silent truncation of strings. The format s cuts longer byte strings and pads shorter ones with zero bytes, without warning.
  5. Precision of f. A Python float has double precision, and packing it as f rounds it to single precision.
  6. Exact buffer size. The function unpack rejects a buffer that is longer or shorter than the format; unpack_from reads from a larger buffer.

The third, fourth and fifth pitfalls are reproduced in the following example.

import struct

try:
    struct.pack(">H", 70000)
except struct.error as error:
    print(error)  # Output (CPython 3.12): 'H' format requires 0 <= number <= 65535

print(struct.pack("5s", b"hi"))     # Output: b'hi\x00\x00\x00'
print(struct.pack("2s", b"hello"))  # Output: b'he'

value = struct.unpack("<f", struct.pack("<f", 0.1))[0]
print(value == 0.1, round(value, 7) == 0.1)  # Output: False True

The unsigned short accepts values from 0 to 65535, and the error message states the range. The name hi is padded to five bytes and hello is cut to two, so a field that is too short loses data without any error, which makes it necessary to validate lengths before packing. The value 0.1 returns as 0.10000000149011612 after a round trip through four bytes, which is acceptable for coordinates in a graphics format but not for monetary amounts.

Choosing a Binary Tool

Consequently, struct fits records with a fixed layout, while other tools of the standard library cover neighbouring cases, as the following table summarizes.

Situation Recommended approach
A record with several fields of fixed size struct.pack and struct.unpack with an explicit prefix
The same layout used many times A Struct object
Records inside a large buffer unpack_from, pack_into or iter_unpack, over a memoryview
A single integer int.to_bytes and int.from_bytes
A homogeneous array of numbers The module array
Passing a structure to a C function ctypes.Structure
Exchanging data between Python programs json or pickle, not a hand-made layout

Conclusion

It is concluded that the module struct translates between Python values and binary records through a format string that states the type, the order and the position of every field, and that the prefix of that string decides whether the layout follows the conventions of the machine or a standard that every machine reads in the same way. This magic depends on the format being exact, because the bytes carry no description of themselves and a wrong prefix, size or length produces valid data with another meaning. The layouts described here are also the way in which compiled code sees Python data, and writing such code as a C extension module is developed in a future article of this series.