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:

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

Leave a comment

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