How to convert to and from bytes in Python

A typical scenario in systems programming is to read and write structures and data in a certain binary format. This could be using buffers in memory or binary files on disk. This is pretty straightforward to do in C or C++, all you need is a pointer to the start of the structure or data and the number of bytes to copy or write from that pointer. The struct module can be used to achieve the same in Python.

The pack method can be used to convert data to a byte string. For details of the parameters and formatting flags passed to this method, see here. This byte string can be then be passed on the network or written to a binary file. For example:

To read back binary data or data stored in bytes, use the unpack method. The usage of that is similar to above.

Tried with: Python 2.7.6 and Ubuntu 14.04


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

This site uses Akismet to reduce spam. Learn how your comment data is processed.