Binary data is a sequence of bytes interpreted according to a format that specifies the meaning of each field.
Use buffers and struct to inspect sizes, byte order and padding, and validate an envelope before trusting its fields.
The sensor sends twenty header bytes, not a line of text. To read them, we need a layout: which bytes belong to each field, how wide the field is, and which byte comes first. We will unpack one header, then distinguish a readable layout from a valid measurement.

Read the pump's 20-byte header
Every hour a pump sensor uploads a compact file: no encoding to guess, just
a header followed by records. struct.Struct pre-builds a format once —
worth doing when you'll unpack thousands of records — and pack/unpack
convert the whole layout together:
pump-07 is 7 characters in an 8-byte field: pack pads s fields with
NUL bytes on the way out, so you strip them on the way back in. A real file
is a header followed by records, so you rarely have exactly one layout's
worth of bytes — unpack insists on an exact length and raises if there's
anything left over. unpack_from(fmt, buffer, offset) reads from a
position and ignores the rest, which is how you walk a buffer record by
record:
Run it and read the struct.error. Then read the first record without trimming the data by hand.
unpack_from(fmt, buffer, offset) is how you walk a buffer: read a record at
offset, add the record size, repeat. Step through it:
The temperature is stored as a signed short in hundredths — 2150 means
21.50°C, -325 means -3.25°C. For records packed back to back,
RECORD.iter_unpack(data) does this loop for you.
Preparing this topic’s interactive investigation…
Tell big-endian from little-endian
A field only means one number if reader and writer agree on byte order. Mix them up and the bytes don't change — the number they mean does:
print(int.from_bytes(b"\x01\x00", "little"), int.from_bytes(b"\x01\x00", "big"))That's not a hypothetical: a telemetry header written by a big-endian
sensor and read with a little-endian format string doesn't crash — it just
silently reports the wrong record count, three readings misread as 768. The
< or > at the front of a struct format isn't decoration; it's the
contract between whoever wrote the file and whoever reads it, possibly on
different hardware, possibly years apart.
Signed numbers use two's complement — you rarely compute it by hand,
you just ask for signed=True (or the signed struct code, lower-case)
whenever a field can go negative, like a temperature:
Pad a struct without meaning to
The </> prefix also turns off something you'd never choose on purpose:
native alignment. Without a prefix, struct uses the machine's own
rules, which insert padding so bigger fields start on tidy memory
boundaries:
import struct
print(struct.calcsize("@BI"), struct.calcsize("<BI"))For integer fields, struct.pack checks the field's range and raises
rather than silently wrapping:
A field that's too narrow for the values it needs to hold is an overflow
waiting to happen — timestamps are the classic case: seconds since 1970,
stored in a fixed number of bits, roll over once seconds have
passed. A signed 32-bit field rolls over in 2038; Quarry's header stores the
timestamp as an unsigned uint32 (I), which buys until 2106.
Validate the envelope before trusting the fields
Unpacking is a layout operation. It can successfully return values from a corrupt or unsupported file. A robust reader asks three questions in order: are enough bytes present, does the header describe a supported format, and does the payload agree with the header?
Suppose the header claims three records of seven bytes each. The expected complete length is 20 + 3 * 7 = 41 bytes. A 40-byte file has a truncated final record; a 42-byte file has one unexplained byte. The exercise that reports leftover intentionally exposes that difference rather than silently discarding it.
Length validation comes before unpacking, but semantic checks follow it: a version must be supported; humidity 250 fits an unsigned byte but violates a 0–100% domain rule. struct checks representability, not the physical meaning of a measurement. For fixed-width string fields, packing can truncate an overlong value, so validate length before packing identifiers you must preserve.
Extend the investigation: take two complete records, remove the final byte, and decide whether your consumer should reject the file or retain complete records with an explicit partial-data flag. Either policy needs a visible result. Do not label a truncated upload “two successful readings”. A checksum can reveal some accidental corruption; the small checksum in read_frames does not authenticate who sent a frame.
Reference: standard versus native layouts and buffer sizes.
Quick practice
import struct
print(struct.pack("<Hh", 65535, -1).hex())Run it and read the struct.error about the buffer size. Fix the call, not the data, so unpacking succeeds.
print((-2).to_bytes(2, "big", signed=True).hex())import struct
HEADER = struct.Struct("<4sB")
print(HEADER.size, struct.calcsize(">4sB"))🎯 Your turn
Build read_header(hex_data):
read_header("5152593101000300803bb16a70756d702d303700")→{"version": 1, "flags": 0, "records": 3, "timestamp": 1790000000, "sensor": "pump-07"}- a PNG's first bytes →
{"error": "bad magic"}
Hint — check len(data) < HEADER.size, unpack_from, compare the magic with
b"QRY1", then sensor.rstrip(b"\x00").decode("ascii").
Then press ▶ Run and hit ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write u16_both(n) returning [little, big]: the number as 2 bytes little-endian and big-endian, each as a hex string. u16_both(258) → ["0201", "0102"].
The header's flags byte packs four switches: bit 0 compressed, bit 1 encrypted, bit 2 partial, bit 3 test. Write decode_flags(value) returning the names of the bits that are set, in bit order. Unknown higher bits are ignored.
A reading is packed as "<HhB": sensor id (uint16), temperature in hundredths of a degree (int16, so it can go negative) and humidity percent (uint8). Write pack_reading(sensor_id, temp_c, humidity) returning the packed bytes as hex, or "out of range" if a value doesn't fit its field. pack_reading(7, 21.5, 40) → "0700660828".
After the header come records of "<IhB" — timestamp, hundredths of a degree, humidity — 7 bytes each. Write parse_records(hex_data) returning {"records": [[timestamp, temp_c, humidity], ...], "leftover": n} where temp_c is the temperature in degrees and leftover counts trailing bytes that don't make a full record.
A stream holds frames back to back: b"QF", a uint16 little-endian payload length, the payload, then a one-byte checksum equal to sum(payload) % 256. Write read_frames(hex_stream) returning {"payloads": [hex, ...], "bad": n, "skipped": k, "truncated": bool}: payloads of frames whose checksum matches, a count of those that don't, a count of bytes skipped while hunting for QF, and whether the stream ended mid-frame. Slice through a memoryview so payloads aren't copied until you keep one.
Quarry's header format is "<4sBBHI8s". A teammate drops the < because "it works on my machine". Explain what the < changes — byte order and padding — and what happens when the file is read somewhere else.