Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

The bitarray Python module

📅 2015-Jan-02 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

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:

print(ba.endian())

To initialize a bitarray from a byte string:

ba.frombytes(byte_str)

To get or set a specific bit in the bitarray:

ba[9] = 0
print(ba[9])

Tried with: Bitarray 0.8.0, Python 3.4 and Ubuntu 14.04