Packing a structure
suggest changeThe module “struct” provides facilities to pack Python objects as a contiguous chunk of bytes or disassemble a chunk of bytes into Python structures.
The pack function takes a format string and one or more arguments, and returns a bytes object. This looks very much like you are formatting a string except that the output is not a string but a chunk of bytes.
Output:
Native byteorder: little Byte chunk: ‘\x03\x00\x00\x00\x04\x00\x05’ Byte chunk unpacked: (3, 4, 5) Byte chunk: ‘\x03\x00\x00\x00\x04\x00\x05\x00’
You could use network byte order with data received from network or pack data to send it to network.
Output:
Byte chunk native byte order: ‘\x03\x00\x04\x00\x05\x00’
Byte chunk network byte order: ‘\x00\x03\x00\x04\x00\x05’
You can optimize by avoiding the overhead of allocating a new buffer by providing a buffer that was created earlier.
Output:
Byte chunk: ‘\x03\x00\x04\x00\x05\x00\x00\x00’
Byte chunk: ‘\x00\x00\x03\x00\x04\x00\x05\x00’
The source for these outputs is not on the page. On this little-endian interpreter, pack('ihb', 3, 4, 5) is b'\x03\x00\x00\x00\x04\x00\x05' (7 bytes) and unpacks to (3, 4, 5). The 8-byte chunk that ends in an extra \\x00 was not reproduced by that call. pack('hhh', 3, 4, 5) is b'\x03\x00\x04\x00\x05\x00' and pack('!hhh', 3, 4, 5) is b'\x00\x03\x00\x04\x00\x05'. The last two chunks match pack_into('hhh', buf, 0, 3, 4, 5) and pack_into('hhh', buf, 2, 3, 4, 5) on an 8-byte zero buffer. Python 3 prints these as bytes, with a b prefix. Native order is little-endian here; a big-endian machine prints different bytes.