灵感来自https://stackoverflow.com/a/15538456/1219006
n = 2
[[[i>>k&1 for k in range(j, j-8, -1)] for j in range(8*n-1, 0, -8)]
for i in range(2**(8*n))]
您需要在 Python 3 上运行它,n
因为xrange
它不支持大整数。
作为生成器:
def byte_array(n):
for i in range(2**(8*n)):
yield [[i>>k&1 for k in range(j, j-8, -1)] for j in range(8*n-1, 0, -8)]
>>> i = byte_array(4)
>>> next(i)
[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
>>> next(i)
[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1]]
或者,如果您不想将它们分组,则更简单:
[[i>>j&1 for j in range(8*n-1, -1, -1)] for i in range(2**(8*n))]
等效发生器:
def byte_array(n):
for i in range(2**(8*n)):
yield [i>>j&1 for j in range(8*n-1, -1, -1)]