
Recall first from bytes, struct and endianness
- Indexing a bytes object returns an integer, while slicing it returns bytes.
- The struct prefixes < and > select standard field sizes and disable automatic padding.
- iter_unpack requires the buffer length to be a multiple of the record size.
Anatomy of a binary frame
3 min readIn the previous lesson you unpacked individual binary fields with struct. This lesson assembles those fields into a complete frame with a magic number, length and CRC, and rejects corrupt or truncated input before interpretation.
The problem is real on every embedded link you have used in this module. A UART, a socket and a log file all deliver a stream of bytes with no message boundaries. The read(2) man page states it plainly: a successful read may return fewer bytes than requested, for example because fewer bytes are available right now. A sensor reading written as eight raw bytes can arrive as five bytes now and three later, or with one bit flipped by electrical noise on the wire. If you call struct.unpack on whatever arrived, you either crash with struct.error or, worse, silently decode garbage into a plausible-looking temperature. the convention that marks where a message starts, how long it is, and how to verify it before use is what turns an unreliable byte stream into trustworthy records.
The frame format for this lesson is small and typical of sensor protocols:
| Field | Size | struct code | Meaning |
|---|---|---|---|
| magic | 2 bytes | 2s |
fixed marker b"\xa5\x5a" |
| length | 2 bytes | H |
payload size in bytes, little-endian |
| payload | length bytes |
(varies) | the actual data |
| CRC-32 | 4 bytes | I |
checksum over magic + length + payload |
The a fixed byte sequence at a known offset that identifies the protocol and the likely start of a frame here is two bytes chosen to be unlikely in ordinary data. The length field is what makes the format self-delimiting: once you have read the four-byte header, you know exactly how many more bytes belong to this frame. The cyclic redundancy check, a checksum computed from the bytes that detects accidental corruption is computed with zlib.crc32 from the standard library, which implements the same CRC-32 used by Ethernet, PNG and gzip. In Python 3 it returns an unsigned 32-bit integer, ready to pack with I.
Building a frame is pack, concatenate, checksum, append:
import struct
import zlib
MAGIC = b"\xa5\x5a"
HEADER = struct.Struct("<2sH") # magic, payload length
TRAILER = struct.Struct("<I") # CRC-32
MAX_PAYLOAD = 1024
def build_frame(payload: bytes) -> bytes:
head = HEADER.pack(MAGIC, len(payload))
body = head + payload
return body + TRAILER.pack(zlib.crc32(body))
Note what the CRC covers: body is the header plus the payload, not the payload alone. That choice is load-bearing and the next section shows why. The < prefix keeps every multi-byte field little-endian, matching what the previous lesson established and what the byteorder(3) family of conversions in C firmware typically produces on ARM and x86 alike.
Validate before you parse
3 min readValidation order matters because each check protects the next one. You cannot read the length field until you know at least a header's worth of bytes arrived. You cannot slice out the payload until the length is sane. And you cannot trust the payload until the CRC over header and payload matches the stored value.
Minimum size: at least
HEADER.size + TRAILER.size(8) bytes, else the frame is truncated.Magic: the first two bytes equal
b"\xa5\x5a", else these bytes are not our protocol.Length cap: the length field is at most
MAX_PAYLOAD, so a corrupted length cannot make you allocate or wait for gigabytes.Total size: the buffer holds exactly header + length + CRC bytes, no fewer (truncation) and no more (mis-framing).
CRC:
zlib.crc32over header + payload equals the stored trailer value.Only now: slice out the payload and unpack its fields.
def parse_frame(data: bytes) -> bytes:
if len(data) < HEADER.size + TRAILER.size:
raise ValueError("truncated frame")
magic, length = HEADER.unpack_from(data, 0)
if magic != MAGIC:
raise ValueError("bad magic")
if length > MAX_PAYLOAD:
raise ValueError("length over limit")
if len(data) != HEADER.size + length + TRAILER.size:
raise ValueError("size mismatch")
body = data[:HEADER.size + length]
(stored,) = TRAILER.unpack_from(data, HEADER.size + length)
if zlib.crc32(body) != stored:
raise ValueError("CRC mismatch")
return data[HEADER.size:HEADER.size + length]
The return value is the raw payload, still unparsed. Interpretation is a separate step with its own schema. For the sensor log in this session's lab, each payload is one fixed 8-byte record: "<IhH", a uint32 Unix timestamp, an int16 temperature in hundredths of a degree Celsius, and a uint16 relative humidity in hundredths of a percent. Watch the parser accept a good frame and reject two kinds of damage:
payload = struct.pack("<IhH", 1_700_000_000, 2317, 4512)
frame = build_frame(payload)
print(len(frame), frame[:4].hex())
print(struct.unpack("<IhH", parse_frame(frame)))
bad = bytearray(frame)
bad[6] ^= 0x01 # flip one bit inside the payload
for candidate in (bytes(bad), frame[:-1]):
try:
parse_frame(candidate)
except ValueError as exc:
print("rejected:", exc)
16 a55a0800
(1700000000, 2317, 4512)
rejected: CRC mismatch
rejected: size mismatch
The header hex a55a0800 is the magic followed by the length 8 in little-endian order. The bit flip at index 6 lands inside the payload and fails the CRC; dropping the last byte fails the size check before the CRC is even computed. Both failures raise before any payload field is interpreted, which is exactly the property the lab will test.
Never slice, allocate or read based on a length field you have not checked. Cap it (here MAX_PAYLOAD = 1024), then compare it against the bytes you actually hold. A corrupted length that happens to pass the CRC is astronomically unlikely, but a length you never validated against a cap is an invitation to exhaust memory on malformed input.
Framing a stream, not a single buffer
4 min readA sensor log written over a UART is just frame after frame appended to a file. Two extra hazards appear that a single-buffer parser never sees. First, the magic bytes can occur by chance inside a payload (a temperature field can contain 0xa5 0x5a), so finding the magic is a hint, not proof. Second, the file can end mid-frame because the board lost power or the capture was stopped, which is truncation, not corruption, and deserves a different report.
The scanner below searches for the magic, throws out candidates whose length is over the cap, uses the length field to propose a frame end, and lets parse_frame be the judge. A candidate is accepted only if its CRC passes; otherwise the scanner advances one byte past the false magic and searches again:
def iter_frames(data: bytes):
pos = 0
while pos < len(data):
start = data.find(MAGIC, pos)
if start == -1:
return
if len(data) - start < HEADER.size + TRAILER.size:
return # truncated tail
_, length = HEADER.unpack_from(data, start)
if length > MAX_PAYLOAD:
pos = start + 1 # absurd length: false magic, resync
continue
end = start + HEADER.size + length + TRAILER.size
if end > len(data):
return # truncated final frame
try:
yield parse_frame(data[start:end])
except ValueError:
pos = start + 1 # false magic: resync
continue
pos = end
This is length-prefixed framing with CRC validation doing the work: corrupt frames are skipped without ever being interpreted, a truncated tail stops the scan cleanly instead of raising mid-record, and garbage between frames costs at most a byte-by-byte search. In the lab you will point this scanner at a log where single bytes were flipped in two frames and confirm that the good records decode and the bad ones are counted as rejects, not exceptions that kill the run.
Going deeperExplore the mechanism
What does CRC-32 actually guarantee? zlib.crc32 uses the standard CRC-32 polynomial (0x04C11DB7, reflected), the same one as Ethernet, PNG and gzip. It detects every single-bit error and every burst error up to 32 bits long; longer bursts escape with probability roughly 1 in 2^32 for random corruption. That is excellent against wire noise and flash bit-rot, and it is why the check is cheap enough to run on every frame.
It is not a security mechanism. Anyone who can modify the payload can recompute a valid CRC, because the algorithm is public and keyed by nothing. If a frame must be authenticated against a deliberate attacker, that needs a keyed MAC, which is outside this lesson.
Two design rules follow from the guarantees. First, the CRC must cover the header: if it covered only the payload, a corrupted length field would re-slice the frame and the untouched payload bytes could still produce a matching CRC. Second, resynchronisation must revalidate: after a CRC failure the scanner cannot trust the length field it just read, so it steps one byte forward and treats the next magic hit as a fresh candidate. The length cap in parse_frame keeps a corrupted length from proposing an absurd frame size during that search.
You now have the full path from raw bytes to trusted records: frame, validate, then unpack. The lab hands you a binary sensor log and asks for exactly that pipeline, with bad-checksum frames rejected and counted. The next lesson, "NumPy and pandas fundamentals", takes over where this one stops: once frames decode into rows of timestamps and readings, you will want arrays and tables instead of lists of tuples, and that is what NumPy and pandas provide.
Key takeaways
- zlib.crc32 computes the same CRC-32 used by Ethernet, PNG and gzip, and returns an unsigned 32-bit value in Python 3
- The CRC must cover the header (magic and length) as well as the payload, or a corrupted length field can slip through
- Every check (size, magic, length cap, total size, CRC) runs before struct.unpack touches the payload
- Magic bytes can occur inside payload data, so a resynchronising parser accepts a candidate only after its CRC passes
Reflect
- Explain to a colleague, in two sentences: build a binary frame with a magic number, length field, payload and CRC-32 using struct and zlib
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pageread(2): read from a file descriptor
- Man pagebyteorder(3): byte order conversion macros
- Man pageendian(3): byte order conversion
Official documentation first. Links checked when the lesson was published.