struct

Contents

struct#

struct packs and unpacks fixed-layout binary records. The operator’s tool for protocol headers, file formats, and anything where bytes line up at known offsets.

import struct

header = struct.pack(">IHH", session_id, length, flags)
session_id, length, flags = struct.unpack(">IHH", header)

The format string is a sequence of byte-order, type, and count codes. Some common codes.

Code

Meaning

>

Big-endian (network byte order).

<

Little-endian.

!

Network byte order (alias for >).

=

Native, no padding.

@

Native, with native padding (the default).

b / B

signed / unsigned 8-bit

h / H

signed / unsigned 16-bit

i / I

signed / unsigned 32-bit

q / Q

signed / unsigned 64-bit

f / d

32-bit / 64-bit IEEE 754 float

s

bytes; prefix with count, e.g. 16s

x

pad byte (skipped)

A pre-compiled Struct object is faster for repeated pack / unpack and gives you size for the total length.

HDR = struct.Struct(">IHH")
HDR.size                      # 8
buf  = HDR.pack(sid, length, flags)
sid, length, flags = HDR.unpack(buf)

struct.iter_unpack walks a buffer in fixed-size chunks without an explicit loop.

for sid, length, flags in HDR.iter_unpack(stream):
    process(sid, length, flags)

References#