Python Struct Module
The struct module performs conversions between Python values and C structs represented as Python bytes objects. This can be used in handling binary data stored in files or from network connections, among other sources.
Importing the Module
import struct
Packing Data
struct.pack() returns a bytes object containing the values v1, v2, ... packed according to the format string fmt.
import struct
# Pack an integer, two bytes, and a float
packed_data = struct.pack('I 2s f', 1024, b'AB', 3.14)
print(packed_data)
Unpacking Data
struct.unpack() unpacks from the buffer (presumably packed by pack(fmt, ...)) according to the format string fmt. The result is a tuple even if it contains exactly one item.
import struct
packed_data = b'\x00\x04\x00\x00AB\xc3\xf5H@'
unpacked_data = struct.unpack('I 2s f', packed_data)
print(unpacked_data)
# Output: (1024, b'AB', 3.140000104904175)
Format Strings
Format strings are the mechanism used to specify the expected layout when packing and unpacking data.
Byte Order, Size, and Alignment
The first character of the format string can be used to indicate the byte order, size, and alignment of the packed data.
@: Native (default)=: Native<: Little-endian>: Big-endian!: Network (= big-endian)
Format Characters
x: pad bytec: char (bytes of length 1)b: signed char (integer)B: unsigned char (integer)h: short (integer)H: unsigned short (integer)i: int (integer)I: unsigned int (integer)f: floatd: doubles: char[] (bytes)
Calculating Size
struct.calcsize() returns the size of the struct (and hence of the bytes object produced by pack(fmt, ...)) corresponding to the format string fmt.
import struct
size = struct.calcsize('I 2s f')
print(size)