gpt4 book ai didi

python - 寻找一种更优雅的方式将字节转换为位列表

转载 作者:太空宇宙 更新时间:2023-11-04 08:03:50 24 4
gpt4 key购买 nike

我目前正在使用这个小函数将一个字节转换为整数位列表,因为我需要迭代一个字节的单个位。

def byteToBitList(byte):
return [int(bit) for bit in "{0:08b}".format(byte)]

但我认为它不是很优雅。有一个更好的方法吗?可能不使用字符串?

最佳答案

您始终可以从使用 bitwise operations 中获益,它适用于标准整数对象。只需一次将您的数字移动一位并收集最右边的位值。例如:

>>> byte = 0xFC
>>> list_size = 8
>>> [(byte >> i) & 1 for i in range(list_size)][::-1] # reverse this array, since left-most bits are evaluated first.
[1, 1, 1, 1, 1, 1, 0, 0]

使用 IPython 计时:1000000 次循环,最好的 3 次:每次循环 1.54 µs

甚至可以在不反转数组的情况下生成这个列表:

>>> byte = 0xFC
>>> list_size = 8
>>> [(byte & (1 << (list_size - 1 - k))) >> (list_size - 1 - k) for k in range(list_size)]
[1, 1, 1, 1, 1, 1, 0, 0]

使用 IPython 计时:100000 次循环,最好的 3 次:每次循环 2.3 µs。显然,颠倒列表比使用两个类次更快!

此外,this Stack Overflow thread包含一个非常相似的问题。

关于python - 寻找一种更优雅的方式将字节转换为位列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35150287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com