Back
+15 XP
Concept

Packing Binary Data with struct.pack & unpack

The `struct` module converts between Python values and C structs represented as binary bytes. Format specifiers (e.g. `'I'` for 32-bit uint) dictate memory layouts 📦.

python
import struct

# Pack an unsigned 32-bit int (I) and a 16-bit short (H):
packed = struct.pack(">IH", 1024, 42)
print(f"Packed bytes: {packed} (length: {len(packed)} bytes) 📦")

# Unpack back to Python tuple:
unpacked = struct.unpack(">IH", packed)
print(f"Unpacked: {unpacked} ✅")

# 79. Packing Binary Data with struct.pack & unpack The `struct` module converts between Python values and C structs represented as binary bytes. Format specifiers (e.g. `'I'` for 32-bit uint) dictate memory layouts 📦. ```python import struct # Pack an unsigned 32-bit int (I) and a 16-bit short (H): packed = struct.pack(">IH", 1024, 42) print(f"Packed bytes: {packed} (length: {len(packed)} bytes) 📦") # Unpack back to Python tuple: unpacked = struct.unpack(">IH", packed) print(f"Unpacked: {unpacked} ✅") ``` Common format characters: `'b'` (int8), `'h'` (int16), `'i'` (int32), `'q'` (int64), `'f'` (float32), `'d'` (float64), and `'s'` (bytes string)! 📦 --- ### Question Which struct format character packs a standard 4-byte unsigned integer? 🧠 - [ ] a. `'I'` 📦 - [ ] b. `'H'` - [ ] c. `'B'` - [ ] d. `'Q'` --- ### Challenge Import `struct`. Pack integer `500` as a big-endian unsigned 32-bit int (`'>I'`). Unpack it and print the first element of the tuple. 🎯 <details> <summary>Solution</summary> ```python import struct packed = struct.pack(">I", 500) val = struct.unpack(">I", packed)[0] print(val) ``` </details>

Checkpoint

Which struct format character packs a standard 4-byte unsigned integer? 🧠

Practice

Import `struct`. Pack integer `500` as a big-endian unsigned 32-bit int (`'>I'`). Unpack it and print the first element of the tuple. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks