Python struct pack, unpack with Examples

Python struct module is capable of performing the conversions between the Python values and C structs, which are represented as Python Strings.

Python Struct

  • Python struct module can be used in handling binary data stored in files, database or from network connections etc.
  • It uses format Strings as compact descriptions of the layout of the C structs and the intended conversion to/from Python values.

Python Struct Functions

There are five important functions in struct module – pack(), unpack(), calcsize(), pack_into() and unpack_from(). In all these functions, we have to provide the format of the data to be converted into binary.

Some of the popular format characters are:

You can get the complete list of format characters here. Let’s start looking into struct module functions one by one.

Python struct.pack()

This function packs a list of values into a String representation of the specified type. The arguments must match the values required by the format exactly. Let’s quickly look at struct pack() example:

When we run this script, we get the following representation:

python-struct-pack (1)

Note that ‘b’ in the Output stands for binary.

Python struct.unpack()

This function unpacks the packed value into its original representation with the specified format. This function always returns a tuple, even if there is only one element. Let’s quickly look at struct unpack() function example:

When we run this script, we get back our original representation:
python-struct-unpack
Clearly, we must tell the Python interpreter the format we need to unpack the values into.

Python struct calcsize()

This function calculates and returns the size of the String representation of struct with a given format.

Size is calculated in terms of bytes. Let’s quickly look at an example code snippet:

When we run this script, we get the following representation:

Python struct pack, unpack

Python struct pack_into(), unpack_from()

These functions allow us to pack the values into string buffer and unpack from a string buffer. These functions are introduced in version 2.5.

When we run this script, we get the following representation:

Python struct pack, unpack

That’s all for a short introduction of python struct module.

By admin

Leave a Reply

%d bloggers like this: