Python: Handle binary data

165089struct module: pack, unpack

struct

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

 

struct.calcsize(fmt)

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

Example:

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

>>> 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
(16961,)

>>> struct.pack('hhl', 11, 22, 33)
b'\x0b\x00\x16\x00\x00\x00\x00\x00!\x00\x00\x00\x00\x00\x00\x00'
>>> 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')
41

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s