How to convert bitarray to an integer in python

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.


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.


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