Pack Fixed Records with struct
Core idea
struct converts numeric fields to and from fixed binary layouts. A format such as >HB selects big-endian standard sizes, an unsigned two-byte integer and an unsigned one-byte integer. Use an explicit layout for exchanged data.
import structrecord = struct.pack(">HB", 258, 7)print(record.hex(), struct.calcsize(">HB"))print(struct.unpack(">HB", record))The high byte of 258 comes first; unpack returns a tuple.
Decode at an offset
import structraw = bytes.fromhex("ff0201ee")print(struct.unpack_from("<H", raw, 1))Little-endian reads the low byte first, starting one byte into the buffer.
Common mistake
Without a prefix, native size and alignment may vary. unpack requires an exact-size buffer; reject truncated or unexpected records before interpreting them.
Practice
Encode a pair of integers (0–65535 and 0–255) as >HB and return lowercase hex.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Binary layouts
Check your understanding of struct and byte order.
What is printed?
import structprint(struct.pack(">H",258).hex())What is printed?
import structprint(struct.calcsize(">HB"))Which prefix selects little-endian standard layout?
What does struct.unpack return?