The struct module in python allow us to work with binary data.


pack

struct.pack(fmt, v1, v2, ...) Return a bytes object containing the values v1, v2, … packed according to the format string fmt. The arguments must match the values required by the format exactly.

we can use pack method to encode numerical data into formatted binary data.

packed_data = struct.pack('iif', 6, 19, 4.7) # iif → int, int, float
print(packed_data)
b'\x06\x00\x00\x00\x13\x00\x00\x00ff\x96@'

calcsize

struct.calcsize(fmt) Return the size of the struct (and hence of the bytes object produced by pack(fmt, …)) corresponding to the format string fmt.

print(struct.calcsize('c'))
print(struct.calcsize('i'))
print(struct.calcsize('f'))
print(struct.calcsize('cif'))

1
4
4
12

unpack

struct.unpack(fmt, buffer) Unpack from the buffer buffer (presumably packed by pack(fmt, …)) according to the format string fmt. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes must match the size required by the format, as reflected by calcsize().

data = struct.unpack('iif', b'\x06\x00\x00\x00\x13\x00\x00\x00ff\x96@')
print(data)
(6, 19, 4.699999809265137)