Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of bits in Python?

Tags:

python

arrays

bit

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

like image 344
zheric Avatar asked Jul 26 '12 12:07

zheric


People also ask

How do you create an array of binary in Python?

To create a record array from binary data, use the numpy. core. records. fromstring() method in Python Numpy.

What is bit array in Python?

bitarray: efficient arrays of booleans. This library provides an object type which efficiently represents an array of booleans. Bitarrays are sequence types and behave very much like usual lists. Eight bits are represented by one byte in a contiguous block of memory.

How do you create an array of data in Python?

In Python, you can create new datatypes, called arrays using the NumPy package. NumPy arrays are optimized for numerical analyses and contain only a single data type. You first import NumPy and then use the array() function to create an array. The array() function takes a list as an input.


2 Answers

from bitarray import bitarray  a = bitarray(2**20) 

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

like image 53
SJP Avatar answered Oct 07 '22 09:10

SJP


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.

like image 29
Scott Griffiths Avatar answered Oct 07 '22 09:10

Scott Griffiths