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). |
|
signed / unsigned 8-bit |
|
signed / unsigned 16-bit |
|
signed / unsigned 32-bit |
|
signed / unsigned 64-bit |
|
32-bit / 64-bit IEEE 754 float |
|
bytes; prefix with count, e.g. |
|
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#
memoryview for zero-copy slicing of the buffer
structreads.bytes for the underlying bytes type.