import struct – a glance

What is struct in python?

struct is the python module which translates binary string to python types and vice versa. if you have any binary string which comes from network stream or anywhere can be directly translated to python types.

Where it can be used?

Network streaming applications, where it supposed to receive lots of streaming binary content, it can be processed in python with help of this module.

What are the rules?

  1. It has two familiar methods. pack, unpack
  2. It takes data format as one of the input field along with the target data.
  3. Some notables

struct.pack(format_string, data)

struct.unpack(format_string, data)

format_string is used to parse the incoming data into a given format. There are various data formats are possible based on the cpu architecture of the machine(endian-ness) endian.

for example, s represents single char, f – floating point number, I – unsigned integer. There are the codes are used in format identifier. formats


In [88]: py_data = (1, 'navaneethan', 3.14)

In [89]: py_data
Out[89]: (1, 'navaneethan', 3.14)

In [90]: import struct

In [91]: struct.pack('I 11s f', *py_data)
Out[91]: '\x01\x00\x00\x00navaneethan\x00\xc3\xf5H@'

In [92]: hex_rep = struct.pack('I 11s f', *py_data)

In [93]: import binascii

In [94]: binascii.hexlify(hex_rep)
Out[94]: '010000006e6176616e65657468616e00c3f54840'

In [95]: bin_rep = binascii.hexlify(hex_rep)

In [96]: binascii.unhexlify(bin_rep)
Out[96]: '\x01\x00\x00\x00navaneethan\x00\xc3\xf5H@'

In [97]: struct.unpack('I 11s f', hex_rep)
Out[97]: (1, 'navaneethan', 3.140000104904175)

In [103]: struct.unpack('@I 11s f', hex_rep)
Out[103]: (1, 'navaneethan', 3.140000104904175)
# `@` represents native

In [102]: struct.unpack('<I 11s f', hex_rep)
error                                     Traceback (most recent call last)
<ipython-input-102-94050abdb5f6> in <module>()
----> 1 struct.unpack('<I 11s f', hex_rep)

# `<` represents little-endian format, so it failed 

format_string in the above example, I 11s f - ( 1 Unsigned Integer, 11 char string, 1 float value)

Still, hungry?


About Navaneethan

mixed feelings...
This entry was posted in 10min, General, Python and tagged , , . Bookmark the permalink.

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