38

How can I declare a bit array of a very large size, say 6 million bits?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
zheric
  • 475
  • 2
  • 6
  • 10

5 Answers5

45
from bitarray import bitarray

a = bitarray(2**20)

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

SJP
  • 1,330
  • 12
  • 21
29

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.

Scott Griffiths
  • 21,438
  • 8
  • 55
  • 85
11

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]
Felix Weis
  • 7,434
  • 1
  • 12
  • 6
11

Quite easily

bitarray60000 = 1<<60000

With that, you can use bitshift operator to your heart content. For instance, position 2 set True would be:

bitarray60000 | 1<<2

Getting bit from position 2

bitarray60000 & 1<<2

I guess the idea is quite simple. Though some operations might be tricky.

Pavel Hanpari
  • 4,029
  • 2
  • 20
  • 23
9

Get the bitarray module using

pip install bitarray

Then, this code will create a bit array of size 6 million,

from bitarray import bitarray
bit_array = bitarray(6000000)

You can initialize all the bits to zero using

bit_array.setall(0)

To set a particular bit, say bit number 25, to 1, do this:

bit_array[25]=1   
Tarun
  • 2,579
  • 1
  • 13
  • 7
  • 2
    I updated `pip` beforehand see [link](https://packaging.python.org/installing/) Then execute `python -m pip install bitarray` on Windows. – yW0K5o Feb 23 '17 at 19:09