How to convert bitarray to an integer in python

Miriam Farber picture Miriam Farber · Feb 26, 2017 · Viewed 8.7k times · Source

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?

Answer

Stephen Rauch picture Stephen Rauch · Feb 26, 2017

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