Python struct — Pack and Unpack Binary Data
Binary formats store numbers as fixed numbers of bytes in a fixed order: a file header, a network packet, a record on disk. Reading those bytes as text scrambles every value, and slicing them by hand invites off-by-one errors at every field. The struct module handles both directions with no package to install: pack turns values into bytes under a format string, and unpack turns the same bytes back into values. This guide takes those parts in turn, then byte order and alignment, the format characters, buffers, and the Struct class.
Written November 17, 2026 · Tested with Python 3.12.3 · 4 min read
- The main program: pack and unpack
- Byte order, size, and alignment: the prefixes and calcsize
- Integer format characters
- Floats, characters, strings, padding, and Pascal strings
Written November 17, 2026
Tested with Python 3.12.3
What this guide is
The struct module converts between Python values and bytes, under a format string that names the type and order of each field. It does not read files or sockets itself: it produces the bytes a program writes, and it reads the bytes a program received. That makes it the right tool for binary file headers, network protocols, and any fixed-layout record where a field is, for example, a 4-byte signed integer followed by a 2-byte signed integer, with no separators and no text encoding to lean on.
The main program: pack and unpack
A format string lists one character per field. Here <ih means little-endian byte order, a standard 4-byte signed integer (i), then a standard 2-byte signed integer (h). pack returns the bytes, shown as hex so every byte is visible, and unpack with the same format returns the original values as a tuple. The > prefix is big-endian, and ! is network order, which is big-endian under another name:
import struct
packed = struct.pack("<ih", 258, -3)
print(packed.hex())
print(struct.unpack("<ih", packed))
print(struct.pack(">ih", 258, -3).hex())
print(struct.pack("!ih", 258, -3).hex())
print(struct.pack("<hi", -3, 258).hex(), struct.pack(">hi", -3, 258).hex())
The exact output:
02010000fdff
(258, -3)
00000102fffd
00000102fffd
fdff02010000 fffd00000102
Byte order changes the bytes, not the values: 258 is 02010000 little-endian and 00000102 big-endian, and -3 is fdff little-endian and fffd big-endian — each multi-byte field has its bytes reversed. The last line swaps the field order as well as the byte order, which is why reading a format with the wrong string does not raise an error — it quietly returns wrong numbers. A format string is part of a file or protocol specification, and a program keeps it in one place.
Byte order, size, and alignment: the prefixes and calcsize
The first character of a format string chooses how fields are laid out. @ is native byte order with native alignment: fields are padded so each one starts at an offset matching its own alignment, the way a C compiler lays out a struct. = is native byte order with standard sizes and no alignment. < is little-endian, > is big-endian, and ! is network order; the last three all use standard sizes and no alignment. calcsize reports how many bytes a format occupies under a given prefix:
import struct
for fmt in ("ih", "hi", "ci", "bh"):
print(fmt, struct.calcsize("@" + fmt), struct.calcsize("=" + fmt), struct.calcsize("<" + fmt))
print(struct.calcsize("@ihf"), struct.calcsize("<ihf"))
print(struct.calcsize("3s"), struct.calcsize("10s"), struct.calcsize("x"), struct.calcsize("4x"))
The exact output:
ih 6 6 6
hi 8 6 6
ci 8 5 5
bh 4 3 3
12 10
3 10 1 4
The contrast is in the second and third rows. ih happens to need no padding under @, because the integer comes first and is already aligned, so all three prefixes report 6. hi puts the 2-byte field first, so under @ the integer that follows is padded from offset 2 to offset 4, and the format grows from 6 bytes to 8. ci grows from 5 to 8 for the same reason, and adding a float makes @ihf 12 bytes against 10 packed. The last line covers the counted formats: a number before s is the exact byte count of the string field, and x is a pad byte that stores nothing and returns nothing, so 4x is 4 bytes of padding. The practical rule follows directly: a format that describes bytes on disk or on a wire names <, >, or ! explicitly, because @ depends on the platform that runs the code.
Integer format characters
Each integer character fixes a size and a signedness. Lowercase is signed and uppercase is unsigned: b and B are 1 byte, h and H are 2, i and I are 4, and q and Q are 8. l and L are 4 bytes in standard size, but under native alignment an l occupies the platform's C long size, which the middle line shows as 8. A count before a character repeats it, so 3h is three shorts:
import struct
print(struct.pack("<bB", -5, 250).hex())
print(struct.pack("<hH", -1000, 60000).hex())
print(struct.pack("<iI", -70000, 4000000000).hex())
print(struct.calcsize("<l"), struct.calcsize("<L"), struct.calcsize("@l"))
print(struct.pack("<qQ", -5000000000, 18000000000000000000).hex())
values = (-5, 250, -1000, 60000, -70000, 4000000000)
print(struct.unpack("<bBhHiI", struct.pack("<bBhHiI", *values)) == values)
The exact output:
fbfa
18fc60ea
90eefeff00286bee
4 4 8
000efad5feffffff000008c5a1d8ccf9
True
The round trip on the last line is exact for integers: pack and unpack with the same format return the values that went in. Picking a character too small for a value is an error at pack time, covered below, not a silent wrap. One character sits outside the standard table: P packs a pointer-sized integer, it is valid only with native byte order, and it has no standard size, so formats meant to travel between machines never use it.
Floats, characters, strings, padding, and Pascal strings
The remaining characters cover the non-integer fields. f is a 4-byte float and d is an 8-byte double, both in the byte order the prefix selects. c is a single byte, passed and returned as a bytes object of length 1. A counted s is a fixed-width byte string: a shorter value is padded with null bytes, and a longer one is truncated to the count. A counted p is a Pascal string, stored as a length byte followed by the data, inside a total field of the counted size. x skips a byte on unpack and writes a zero byte on pack, taking no value in either direction:
import struct
print(struct.unpack("<fd", struct.pack("<fd", 1.5, 2.25)))
print(struct.pack("<c3s", b"A", b"hi"))
print(struct.pack("<4s", b"hi"))
print(struct.pack("<6p", b"hello"))
print(list(struct.pack("<xcx", b"Z")))
print(struct.unpack("<xcx", bytes([0, 90, 0])))
The exact output:
(1.5, 2.25)
b'Ahi\x00'
b'hi\x00\x00'
b'\x05hello'
[0, 90, 0]
(b'Z',)
Two lines carry the cautions. The 4s line shows the padding directly: hi in a 4-byte field is stored with two null bytes after it, and unpack returns all 4 bytes, so a reader strips the padding itself when the field is text. The float line round-trips exactly only because 1.5 and 2.25 are values a binary float represents exactly; a value such as 0.1 comes back as the nearest float or double, not as the decimal that was typed, and an f field holds less precision than a d field holding the same input.
The trap: unpack requires an exact size
unpack accepts a buffer of exactly the format's size — no shorter, and no longer. Both mistakes raise struct.error with the same message naming the required size. Packing a value outside a character's range raises struct.error as well:import struct
print(struct.calcsize("<ih"))
for data in (b"\x01\x00", b"\x01\x00\x00\x00\x00\x00\x00"):
try:
struct.unpack("<ih", data)
except struct.error as e:
print(type(e).__name__ + ":", e)
try:
struct.pack("<B", 300)
except struct.error as e:
print(type(e).__name__ + ":", e)
The exact output:
6
error: unpack requires a buffer of 6 bytes
error: unpack requires a buffer of 6 bytes
error: 'B' format requires 0 <= number <= 255
The exact-size rule is why code that reads a stream checks the length it got before it unpacks, and why a truncated file surfaces as this error rather than as a half-filled record. When a buffer holds a record plus more data after it, the answer is not to slice by hand as a first resort — the offset functions in the next section read a record from the middle of a buffer directly.
Reading and writing inside a buffer: pack_into and unpack_from
pack_into writes values into a writable buffer, such as a bytearray, at a given offset, and unpack_from reads values from any buffer starting at an offset. Together they handle a record embedded in a larger block — a header inside a page of data, or one field inside a header — without copying slices:
import struct
buffer = bytearray(10)
struct.pack_into("<ih", buffer, 2, 258, -3)
print(list(buffer))
print(struct.unpack_from("<ih", buffer, 2))
print(struct.unpack_from("<h", buffer, 0))
print(struct.unpack_from("<h", buffer, 6))
The exact output:
[0, 0, 2, 1, 0, 0, 253, 255, 0, 0]
(258, -3)
(0,)
(-3,)
The record sits at bytes 2 through 7 of the buffer, with zeros left untouched on both sides. The last two lines read single fields back out by their offsets: offset 0 reads the untouched padding as 0, and offset 6 lands on the short field and returns -3. Offsets are in bytes from the start of the buffer, and they follow the same layout the format string describes, padding included under @.
Reusing a format: the Struct class and iter_unpack
A format used more than once belongs in a Struct object. The object pre-parses the format, exposes its size as size, and carries pack, unpack, pack_into, and unpack_from methods with the format already filled in. Its iter_unpack method reads a buffer that holds whole records back to back, yielding one tuple per record; the buffer size must be a multiple of the record size:
import struct
record = struct.Struct("<ih")
print(record.size)
print(record.pack(258, -3).hex())
print(record.unpack(bytes.fromhex("02010000fdff")))
data = struct.pack("<ihihih", 1, 2, 3, 4, 5, 6)
print(list(record.iter_unpack(data)))
try:
list(record.iter_unpack(b"\x01\x00\x00"))
except struct.error as e:
print(type(e).__name__ + ":", e)
The exact output:
6
02010000fdff
(258, -3)
[(1, 2), (3, 4), (5, 6)]
error: iterative unpacking requires a buffer of a multiple of 6 bytes
iter_unpack is the natural reader for a file or packet that is a run of identical records: one Struct names the record once, and the loop over the iterator names no offsets at all. A trailing partial record is an error, as the last line shows, which makes a truncated final record visible instead of silently dropped.
Which choice for which job
| Job | Choice | Why |
|---|---|---|
| Values to bytes, or bytes to values, once | pack and unpack |
The format string travels with the call |
| The size of a format before reading | calcsize |
Reports the byte count under the chosen prefix |
| A format used across a program | The Struct class |
Parses the format once and exposes size and the pack methods |
| A record inside a larger buffer | pack_into and unpack_from |
Reads and writes at a byte offset with no slicing |
| A run of identical records | iter_unpack |
Yields one tuple per record and rejects a partial record |
| Bytes on disk or on a wire | An explicit <, >, or ! prefix |
Standard sizes and no alignment, the same on every platform |
Checklist
- Name the byte order in every format that describes stored or transmitted bytes; never rely on the default
@. - Check a buffer's length before
unpack, and expectstruct.errorwhen it is not exactly the format size. - Pick each integer character by size and signedness, and let a pack-time range error surface instead of masking it.
- Remember that a counted
sfield pads short values with null bytes and truncates long ones. - Use
pack_intoandunpack_fromfor a record inside a larger buffer instead of slicing copies. - Put a repeated format in a
Struct, and read a run of records withiter_unpack.
Related guides on this site
- Python files — open, read, and write — reading the bytes from a file that this module then unpacks, and writing packed bytes back.
- Python base64 — encode, decode, and urlsafe — turning packed bytes into text that survives transport as characters.
- Python ipaddress — networks, hosts, and subnets — the address values that network-order fields so often carry.
- Python json — dumps and loads — the text format to reach for when a record does not need a fixed binary layout.
Sources
- Python Standard Library,
struct—pack,unpack,pack_into,unpack_from,calcsize, anditer_unpack, the byte-order, size, and alignment prefixes, the format characters and their standard sizes, and theStructclass.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.