struct module in Python: Pack and Unpack Data

When you work with binary data, you need a way to map Python values to bytes and read them back. Python’s struct module does this using a format string that describes the data layout.

This article shows how to choose a format and pack and unpack a record. It also explains how to check the byte order and buffer length.

TL;DR: Python struct Module

The struct module turns Python values into packed bytes and reads bytes back according to a format string.

  • Choose a prefix such as ! for network byte order or < for little-endian files.
  • Use pack() to encode and unpack() to decode a buffer of exactly the format’s size.
  • Check that size with calcsize() before reading a record.

What Is the Python struct Module?

Network protocols often specify their byte order explicitly, avoiding dependence on a machine’s native layout.

The prefix table summarizes common format options.

Format partMeaningUse
!Network byte order, standard sizes, no native alignmentProtocol-defined records
< or >Little-endian or big-endian, standard sizesFiles with a stated byte order
@Native byte order, sizes and alignmentMatching a local C layout
2s, ITwo-byte string, unsigned integerField codes in order

The prefix table summarizes common format options.

How to Pack and Read a Binary Record Step by Step

For a fixed record, write down each field’s type and width before choosing its format code.

Step 1: Define the record layout

The ! prefix sets network byte order and avoids the native alignment behavior shown below.

Step 2: Pack and unpack the values

I ran python3 struct_roundtrip_demo.py with !H2sI. It returned these exact lines:

format: !H2sI
size: 8
bytes: 01 bb 4f 4b 00 00 04 b0
decoded: (443, b'OK', 1200)
Terminal output showing struct.pack and struct.unpack round trip

The byte sequence occupies eight bytes, matching the widths specified by this format. I use the same format for packing and unpacking so both sides agree on the layout.

calcsize() gives the bytes required by a format. When a header precedes records in one buffer, unpack_from() starts at a byte offset. The round-trip output above confirms this format needs eight bytes.

For complete records of one repeated layout, iter_unpack() yields a tuple for each record. The buffer length must be an exact multiple of the format size, so handle any header or trailing partial data first.

Check Byte Order, Size and Buffer Limits

Check that the input is a complete record before unpacking.

I compared @HcH with !HcH by running python3 struct_layout_probe.py. The native format measured six bytes while the network format measured five. On this host, native alignment inserted a pad byte before the final short.

@HcH size: 6
!HcH size: 5
native bytes: bb 01 58 00 b0 04
network bytes: 01 bb 58 04 b0
Terminal comparison of native and network struct layouts

The comparison reports the measured sizes and bytes for both layouts.

CaseSymptomResponse
Wrong prefixDecoded integer is wrong without an exceptionMatch the producer’s byte order, such as > or <
Short bufferstruct.error says required buffer lengthRead at least calcsize(format) bytes
Out-of-range valuestruct.error during packingUse a fitting signed or unsigned field code
Native paddingSize differs across layouts or machinesUse a standard prefix and explicit padding when the specification requires it

I passed two bytes to unpack(“!I”, …) in python3 struct_short_buffer_demo.py. The result was error: unpack requires a buffer of 4 bytes.

Terminal output for struct unpack with a short buffer

The !I example needs four bytes, while I supplied only two. Use calcsize() when determining the input size.

For a one-field format, unpack() produces a one-item tuple. Use the assignment value, = struct.unpack(“!I”, data) to get the scalar.

Conclusion

Choose a documented byte order, then handle any incomplete reads from the stream.

For field definitions and platform behavior, consult the Python struct documentation. The AskPython guide to struct.pack() for creating packets continues with packet construction, while its guide to Python bytes objects covers the buffer type used here.

FAQ

These answers cover a few format choices that commonly need a quick check.

What does struct.pack() return?

It returns a bytes object containing values encoded according to the supplied format string.

Why does struct.unpack() require a particular buffer length?

The buffer length must equal struct.calcsize(format), because unpack() reads one complete fixed-size record.

Which prefix should I use for network data?

Use ! for network byte order, which is big-endian and uses standard sizes without native alignment.

Vijaykrishna Ram
Vijaykrishna Ram
Articles: 99