pythonbit-manipulationbitarray

How to convert bitarray to an integer in python


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?


Solution

  • 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