Binary packing (struct)¶
Packing (and unpacking, of course) of data into byte sequences with predefined sizes for each data element, their order in the structure, as well as byte order for multi-byte data types. It's needed for interaction between Python programs and C or C++ code, and allows converting Python's int into, for example, short int or long int in C (details about the C programming language type system).
When working with structures, you'll need to understand what little-endian and big-endian are, and also remember that the size of data types in C can vary.
In [2]:
from struct import pack, unpack, iter_unpack
b = pack('>hhll', 1, 2, 3, 4)
print(b)
t = unpack('>hhll', b)
print(t)
i = pack('ii', 1, 2) * 5
print(i)
print(list(iter_unpack('ii', i)))
b'\x00\x01\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04' (1, 2, 3, 4) b'\x01\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00' [(1, 2), (1, 2), (1, 2), (1, 2), (1, 2)]