How to convert bitarray to an integer in python

10,552

Solution 1

To convert a bitarray to its integer form you can use the struct module:

Code:

from bitarray import bitarray
import struct

d = bitarray('0' * 30, endian='little')

d[5] = 1
print(struct.unpack("<L", d)[0])

d[6] = 1
print(struct.unpack("<L", d)[0])

Outputs:

32
96

Solution 2

from bitarray import bitarray
d=bitarray('0'*30)
d[5]=1

i = 0
for bit in d:
    i = (i << 1) | bit

print i

output: 16777216.

Solution 3

A simpler approach that I generally use is

d=bitarray('0'*30)
d[5]=1
print(int(d.to01(),2))

Code wise this may not be that efficient, as it converts the bit array to a string and then back to an int, but it is much more concise to read so probably better in shorter scripts.

Solution 4

Bitarray 1.2.0 added a utility module, bitarray.util, which includes a functions converting bitarrays to integers and vice versa. The functions are called int2ba and ba2int. Please see here for the exact details: https://github.com/ilanschnell/bitarray

Solution 5

As Ilan Schnell pointed out there is a ba2int() method found in the bitarray.util module.

>>> from bitarray import bitarray
>>> from bitarray.util import ba2int
>>> d = bitarray('0' * 30)
>>> d[5] = 1
>>> d
bitarray('000001000000000000000000000000')
>>> ba2int(d)
16777216

From that same module there is a zeros() method that changes the first three lines to

>>> from bitarray import bitarray
>>> from bitarray.util import ba2int, zeros
>>> d = zeros(30)
Share:
10,552
Miriam Farber
Author by

Miriam Farber

Applied Math PhD Student at MIT

Updated on June 05, 2022

Comments

  • Miriam Farber
    Miriam Farber almost 2 years

    Suppose I define some bitarray in python using the following code:

    from bitarray import bitarray
    d=bitarray('0'*30)
    d[5]=1
    

    How can I convert d to its integer representation? In addition, how can I perform manipulations such as d&(d+1) with bitarrays?

  • Pouya BCD
    Pouya BCD over 4 years
    I like this solution the most as it does not deal with string processing. Also if you can built up your integer bit by bit starting from most significant digit, then you do not need bitarray too.
  • Erik Swan
    Erik Swan almost 4 years
    Any reason these are defined as utility functions instead of methods on the bitarray object, like tobytes()?