Python Reference ยท Standard Library: Math, Data and Text
The struct module
Reference for Python's struct module: convert between Python values and packed binary bytes with format characters, byte order, alignment and calcsize.
The struct module converts between Python values and C-style packed binary data. You describe a layout with a short format string (for example "<HI": a little-endian 2-byte unsigned integer followed by a 4-byte unsigned integer) and then pack() values into bytes or unpack() bytes back into a tuple.
It is the tool for binary file formats (image headers, audio files), network protocols and talking to C libraries, where each field has an exact size and byte order.
import struct data = struct.pack("<HI", 513, 1) print(data) # b'\x01\x02\x01\x00\x00\x00' print(struct.unpack("<HI", data)) # (513, 1)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Format strings
A format string starts with an optional byte order character, followed by format characters, each optionally preceded by a repeat count (3H means three H).
| Prefix | Byte order, size, alignment |
|---|---|
@ (default) |
Native order, native sizes, native alignment (padding between fields). |
= |
Native order, standard sizes, no padding. |
< |
Little-endian, standard sizes, no padding. |
> or ! |
Big-endian (! is network order), standard sizes, no padding. |
| Char | C type | Python type | Standard size |
|---|---|---|---|
x |
pad byte | no value | 1 |
b / B |
signed / unsigned char | int | 1 |
? |
bool | bool | 1 |
h / H |
short | int | 2 |
i / I |
int | int | 4 |
l / L |
long | int | 4 |
q / Q |
long long | int | 8 |
e / f / d |
half / float / double | float | 2 / 4 / 8 |
s |
char array | bytes | the count (5s is 5 bytes) |
c |
char | bytes of length 1 | 1 |
n / N |
ssize_t / size_t | int | native mode only |
P |
void pointer | int | native mode only |
Functions
| Name | Returns |
|---|---|
pack(format, v1, v2, ...) |
A bytes object. |
unpack(format, buffer) |
A tuple. The buffer size must match calcsize(format) exactly. |
unpack_from(format, buffer, offset=0) |
A tuple, reading from a position; the buffer may be longer. |
iter_unpack(format, buffer) |
An iterator of tuples; the buffer size must be a multiple of the record size. |
calcsize(format) |
The size in bytes. |
pack_into(format, buffer, offset, ...) |
Writes into a writable buffer such as a bytearray. |
Struct(format) |
A precompiled format with the same methods and a .size attribute. |
struct.error |
The exception raised for bad formats, wrong sizes and out-of-range values. |
Usage notes
- Always give a byte-order prefix when you handle files or network data. The default
@mode uses native sizes and inserts padding, socalcsize("HI")is 8 whilecalcsize("<HI")is 6. unpackalways returns a tuple, even for a single value:struct.unpack("<I", data)[0].- Strings are bytes. Encode text first (
"hi".encode());spads short values with zero bytes and truncates long ones. Usepfor Pascal strings with a length byte. - Values must fit.
pack("<B", 300)raisesstruct.error. Floats ine/fare rounded to the smaller precision. - For a single integer,
int.to_bytes()andint.from_bytes()are simpler.structshines with several fields at once. - Compile repeated formats with
Struct; the module caches recent formats, but aStructobject states the intent. - No security risk from
structitself, but verify lengths read from untrusted data before using them to slice or allocate.