Python: Handle binary data

165089struct module: pack, unpack


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.


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



Return the size of the struct (and hence of the bytes object produced bypack(fmt, ...)) corresponding to the format string fmt.


fmt table:

Screen Shot 2017-09-21 at 16.54.52


>>> import struct
>>> struct.pack('B', 65)
>>> struct.pack('BB', 65, 66)

>>> struct.unpack('h', b'A')     # refer to the table above
Traceback (most recent call last):
 File "<pyshell#8>", line 1, in <module>
 struct.unpack('h', b'A')
struct.error: unpack requires a bytes object of length 2

>>> struct.unpack('h', b'AB')    # correct

>>> struct.pack('hhl', 11, 22, 33)
>>> struct.unpack('hhl', b'\x0b\x00\x16\x00\x00\x00\x00\x00!\x00\x00\x00\x00\x00\x00\x00')
(11, 22, 33)

>>> struct.calcsize('hhhhhlllB')



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s