How to create an array of bits in Python?

from bitarray import bitarray

a = bitarray(2**20)

You can check out more info about this module at http://pypi.python.org/pypi/bitarray/


This one-liner converts bytes to a list of True/False bit values. Might be not performant for 6M bits but for small flags it should be fine and does not need additional dependencies.

>>> flags = bytes.fromhex(b"beef")
>>> bits =  [flags[i//8] & 1 << i%8 != 0 for i in range(len(flags) * 8)]
>>> print(bits)
[False, True, True, True, True, True, False, True, True, True, True, True, False, True, True, True]

The bitstring module may help:

from bitstring import BitArray
a = BitArray(6000000)

This will take less than a megabyte of memory, and it's easy to set, read, slice and interpret bits. Unlike the bitarray module it's pure Python, plus it works for Python 3.

See the documentation for more details.

Tags:

Python

Arrays

Bit