typestar

Binary data with struct in Python

Packing and unpacking C-style binary records.

import struct

packet = struct.pack(">HHI", 80, 443, 1500)
size = struct.calcsize(">HHI")

src_port, dst_port, length = struct.unpack(">HHI", packet)

record = struct.pack("<f?", 3.14, True)
pi, flag = struct.unpack("<f?", record)

header = struct.Struct(">4sB")
blob = header.pack(b"TYPE", 7)

How it works

  1. Format codes like >HHI set order and field types.
  2. pack builds bytes; unpack reverses it.
  3. A Struct object reuses a compiled format.

The run, in numbers

Lines
12
Characters to type
293
Tokens
95
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 52 seconds.

Type this snippet

Step 5 of 5 in Data formats, step 21 of 41 in Domain tools.

← Previous Next →