我目前正在使用这个小函数将一个字节转换为整数位列表,因为我需要迭代一个字节的单个位。
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包含一个非常相似的问题。
