The struct module packs values according to a format string and unpacks bytes in the opposite direction. A prefix such as > fixes big-endian order and standard sizes instead of relying on the host platform.
from struct import calcsize, pack, unpack
FORMAT = ">Ih" # network byte order: unsigned int, short
payload = pack(FORMAT, 42, -7)
identifier, delta = unpack(FORMAT, payload)
assert len(payload) == calcsize(FORMAT)
print(identifier, delta)
How to use it safely
Define the format in one place, verify calcsize, and reject buffers of unexpected length. For repeated records, iter_unpack avoids manual slicing. Never consider untrusted binary data valid merely because unpacking succeeded.
To strengthen the foundation, read Python collections guide and type hints guide.
The official Python documentation, accessed July 22, 2026, describes the API, edge cases, and version compatibility.