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.
Code
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 bytesWhat 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
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.CSS Flexbox PlaygroundInteractively test CSS flexbox container and item properties with a live preview. Adjust justify-content, align-items, flex-direction, and flex-grow to see layout changes.CSS Grid PlaygroundExperiment with CSS grid layout properties interactively. Define columns, rows, gaps, and areas while watching the grid template update in a live visual preview.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.