简体   繁体   English

如何将位数组转换为 python 中的 integer

[英]How to convert bitarray to an integer in python

Suppose I define some bitarray in python using the following code:假设我使用以下代码在 python 中定义了一些位数组:

from bitarray import bitarray
d=bitarray('0'*30)
d[5]=1

How can I convert d to its integer representation?如何将 d 转换为其 integer 表示形式? In addition, how can I perform manipulations such as d&(d+1) with bitarrays?此外,如何使用位数组执行诸如d&(d+1)之类的操作?

To convert a bitarray to its integer form you can use the struct module:要将bitarray转换为其整数形式,您可以使用struct模块:

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
from bitarray import bitarray
d=bitarray('0'*30)
d[5]=1

i = 0
for bit in d:
    i = (i << 1) | bit

print i

output: 16777216.输出:16777216。

A simpler approach that I generally use is我通常使用的一种更简单的方法是

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

Code wise this may not be that efficient, as it converts the bit array to a string and then back to an int, but it is much more concise to read so probably better in shorter scripts.在代码方面,这可能不是那么有效,因为它将位数组转换为字符串,然后再转换回 int,但它更简洁易读,因此在较短的脚本中可能会更好。

Bitarray 1.2.0 added a utility module, bitarray.util , which includes a functions converting bitarrays to integers and vice versa. Bitarray 1.2.0 添加了一个实用程序模块bitarray.util ,其中包括将位数组转换为整数的函数,反之亦然。 The functions are called int2ba and ba2int .这些函数称为int2baba2int Please see here for the exact details: https://github.com/ilanschnell/bitarray请在此处查看详细信息: https : //github.com/ilanschnell/bitarray

As Ilan Schnell pointed out there is a ba2int() method found in the bitarray.util module.正如Ilan Schnell指出的那样,在bitarray.util模块中有一个ba2int()方法。

>>> 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从同一个模块有一个zeros()方法将前三行更改为

>>> from bitarray import bitarray
>>> from bitarray.util import ba2int, zeros
>>> d = zeros(30)

You can use int :您可以使用int

>>> int(d.to01(), base=2)
>>> 16777216

The bitarray.to01 method produces a bit string from the bit array, and int(<bit string>, base=2) converts it to a decimal integer. bitarray.to01方法从位数组生成一个位串,然后int(<bit string>, base=2)将其转换为十进制数 integer。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM