Python struct: Packing and Unpacking Binary Data
Binary data formats require precise byte-level control. The struct module packs Python values into bytes and unpacks them back. Here is how I use it. Most Python code deals with text and JSON, but binary data appears in file formats, network protocols, and hardware interfaces. The struct module converts between Python values and C-style binary representations. I reach for it when parsing binary file headers, implementing network protocols, or interfacing with C libraries. Format Strings The struct module uses format strings that describe the layout of binary data. Each character represents a type and a byte size. The format string also specifies byte order and alignment. Format C Type Python Size x pad byte none 1 c char bytes (len 1) 1 b/B signed/unsigned char int 1 h/H short int 2 i/I int int 4 f float float 4 d double float 8 s char[] bytes N Byte order is specified by a prefix character at the start of the format string. This matters because different CPU architectures store multi-byte values in different orders. Prefix Byte Order Alignment < little-endian none > big-endian (network) none = native none ! network (big-endian) none Packing Values into…