The bitarray Python module

It is fairly common in many applications to read or write series of bits into bytes or longer array of bytes. For example, to store results of various binary tests. The space saved by storing these results as bits might be crucial when memory or disk resources are the bottleneck.

If you deal with an array of bits, the Python module you need is bitarray.

Installing it for Python 2.x is simple:

$ sudo apt install python-bitarray

If you are using Python 3.x:

$ sudo apt install python3-bitarray

Creating an empty bitarray is easy:

import bitarray
ba = bitarray.bitarray()

Note that the endianess of the data is very important in these applications. bitarray uses big-endian interpretation by default. If your data is stored in little-endian, then specify this explicitly:

ba = bitarray.bitarray(endian="little")

You can check the endianess of any bitarray:


To initialize a bitarray from a byte string:


To get or set a specific bit in the bitarray:

ba[9] = 0

Tried with: Bitarray 0.8.0, Python 3.4 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.