struct Packs Fixed Layout Byte Records

struct.pack and unpack move values into fixed-layout byte strings; iter_unpack walks a buffer without slicing, and wrong sizes raise struct.error.

PythonData Integrity

Code

pythonsnippet
21 lines
import struct

# little-endian (<) unsigned short (H), unsigned int (I), 4-byte string (4s)
record = struct.pack("<HI4s", 7, 65535, b"WAVE")
print("packed bytes:", record)
print("size:", struct.calcsize("<HI4s"))

fields = struct.unpack("<HI4s", record)
print("unpacked:", fields)
print("string field:", fields[2].decode("ascii"))

# iter_unpack walks fixed-size records out of a buffer without slicing by hand
buffer = struct.pack("<HI", 1, 100) + struct.pack("<HI", 2, 200) + struct.pack("<HI", 3, 300)
for row in struct.iter_unpack("<HI", buffer):
    print("row:", row)

# wrong byte count raises struct.error instead of silently truncating
try:
    struct.unpack("<HI", b"\x01")
except struct.error as exc:
    print("error:", exc)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

packed bytes: b'\x07\x00\xff\xff\x00\x00WAVE'
size: 10
unpacked: (7, 65535, b'WAVE')
string field: WAVE
row: (1, 100)
row: (2, 200)
row: (3, 300)
error: unpack requires a buffer of 6 bytes

What the code does

for row in struct.iter_unpack("<HI", buffer) is the loop that carries the per-item work.

The file’s state is a handful of top-level bindings: record, fields, buffer.

Points of care

  • No install step: all APIs used ship with the platform.

Applying it

Each run prints the 3 labeled blocks packed bytes:, size:, unpacked: in source order.

Statements that matter

except struct.error as exc:
    print("error:", exc)

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. Its state lives in module-level bindings: `record`, `fields`, `buffer`.