Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 857
Miriam Farber Avatar asked Feb 26 '17 03:02

Miriam Farber


People also ask

What is Bitarray in Python?

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.

How to change byte to int Python?

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.


2 Answers

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)
like image 152
young_souvlaki Avatar answered Sep 28 '22 03:09

young_souvlaki


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

like image 45
Ilan Schnell Avatar answered Sep 28 '22 04:09

Ilan Schnell