python - Python中的位列表到整数

标签 python arrays list bit-manipulation

我在 Python 中有这样的列表:[1,0,0,0,0,0,0,0]。我可以像输入 0b10000000 那样将其转换为整数(即​​转换为 128)吗? 我还需要将 [1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0] 之类的序列转换为整数(在这里它将返回 0b1100000010000000,即 259)。 如果需要,列表的长度始终是 8 的倍数。

最佳答案

你可以使用位移:

out = 0
for bit in bitlist:
    out = (out << 1) | bit

这很容易胜过 A. R. S. 提出的“int cast”方法,或 Steven Rumbalski 提出的带有查找的修改后的转换:

>>> def intcaststr(bitlist):
...     return int("".join(str(i) for i in bitlist), 2)
... 
>>> def intcastlookup(bitlist):
...     return int(''.join('01'[i] for i in bitlist), 2)
... 
>>> def shifting(bitlist):
...     out = 0
...     for bit in bitlist:
...         out = (out << 1) | bit
...     return out
... 
>>> timeit.timeit('convert([1,0,0,0,0,0,0,0])', 'from __main__ import intcaststr as convert', number=100000)
0.5659139156341553
>>> timeit.timeit('convert([1,0,0,0,0,0,0,0])', 'from __main__ import intcastlookup as convert', number=100000)
0.4642159938812256
>>> timeit.timeit('convert([1,0,0,0,0,0,0,0])', 'from __main__ import shifting as convert', number=100000)
0.1406559944152832

关于python - Python中的位列表到整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12461361/

相关文章:

python - 使用one-hot编码拆分字符串并将df从长格式转换为宽格式

c - 搜索元素的有效方法

c - 如何在 C 中进行位集/字节数组转换

python 和狮身人面像 : bullet point list in multiline google style docstring

python - Psycopg2 中的元命令 -\d 不工作

python - 自动填充 python 列表列表

Python:列表中的唯一项按其出现的顺序排列

java归并排序从最大到最小

python - DRF 更改自定义操作的默认 View 集的lookup_field

python - 如何在 python 中创建列表数组?