How to convert bitarray to 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 to convert d to its integer representation? In addition, how can I perform manipulations such as d&(d+1) with bitrates?

+6
source share
3 answers

To convert a bitarray to its integer form, you can use the struct module:

The 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 
+5
source
 from bitarray import bitarray d=bitarray('0'*30) d[5]=1 i = 0 for bit in d: i = (i << 1) | bit print i 

: 16777216.

+3
source

A simpler approach that I usually use is

 d=bitarray('0'*30) d[5]=1 print(int(d.to01(),2)) 

The code is wise, perhaps not as efficient as it converts the bit array to a string and then back to int, but is much more concise to read, so it is probably better in shorter scenarios.

+1
source

Source: https://habr.com/ru/post/1015280/


All Articles