Introduction
The struct module converts between Python values and C structs packed into bytes. It's used for binary file formats and network protocols.
Pack and Unpack
import struct
# Pack values into bytes
data = struct.pack("i", 42) # int
print(data)
data = struct.pack("3i", 1, 2, 3) # 3 ints
print(data)
data = struct.pack("ii?", 10, 20, True)
print(data)
# Unpack from bytes
unpacked = struct.unpack("i", data)
print(unpacked)
unpacked = struct.unpack("3i", data)
print(unpacked)
Format Strings
import struct
# Byte order: @ (native), = (native, standard), < (little endian), > (big endian), ! (network)
# Types: b (signed char), B (unsigned char), h (short), H (unsigned short),
# i (int), I (unsigned int), q (long long), f (float), d (double), s (char[])
# Little endian int
data = struct.pack("<i", 42)
# Big endian int
data = struct.pack(">i", 42)
# With size prefixes
data = struct.pack("=i", 42)
Struct Objects
import struct
# Create Struct object for efficiency
Header = struct.Struct("III") # 3 unsigned ints
data = b"\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00"
# Unpack
unpacked = Header.unpack(data)
print(unpacked) # (1, 2, 3)
# Pack
packed = Header.pack(1, 2, 3)
print(packed)
# Size
print(Header.size) # 12
Mixed Types
import struct
# Header + data pattern
format = "HHI" # 2 shorts, 1 int (10 bytes total)
header_size = struct.calcsize(format)
# Pack header
header = struct.pack(format, 1, 2, 100)
data = struct.pack(f"{header_size}s", b"Hello")
# Unpack
msg_type, flags, length = struct.unpack(format, header)
message = struct.unpack(f"{length}s", data[header_size:])[0]
Binary File Format
import struct
class WAVReader:
def __init__(self, filename):
with open(filename, "rb") as f:
# RIFF header
self.riff = f.read(4)
self.size = struct.unpack("I", f.read(4))[0]
self.wave = f.read(4)
# fmt chunk
self.fmt = f.read(4)
self.fmt_size = struct.unpack("I", f.read(4))[0]
self.audio_format = struct.unpack("H", f.read(2))[0]
self.num_channels = struct.unpack("H", f.read(2))[0]
self.sample_rate = struct.unpack("I", f.read(4))[0]
Practice Problems
- Pack and unpack integers
- Use different byte orders
- Create Struct objects for reuse
- Read binary file format
- Convert between Python and C structs