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?
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.
To convert bytes to int in Python, use the int. from_bytes() method. A byte value can be interchanged to an int value using the int. from_bytes() function.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With