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
- Format codes like
>HHIset order and field types. packbuilds bytes;unpackreverses it.- A
Structobject 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.
Step 5 of 5 in Data formats, step 21 of 41 in Domain tools.