Skip to content Skip to sidebar Skip to footer

Python : Efficient Bytearray Incrementation

How to iterate all possible values of bytearray of length = n in Python ? in worst case n <= 40bytes For example, iterate for n = 4 : 00000000 00000000 00000000 00000000 0000000

Solution 1:

You can use itertools.product:

In [11]:fromitertoolsimportproductIn [15]:forxinproduct('01',repeat=4):#for your n=4 change repeat to 32 print"".join(x)....:0000000100100011010001010110011110001001101010111100110111101111

Solution 2:

Inspired by https://stackoverflow.com/a/15538456/1219006

n = 2
[[[i>>k&1for k in range(j, j-8, -1)] for j in range(8*n-1, 0, -8)] 
 for i in range(2**(8*n))]

You'll need to run this on Python 3 for large n cause xrange doesn't support big ints.

As a generator:

defbyte_array(n):
    for i inrange(2**(8*n)):
        yield [[i>>k&1for k inrange(j, j-8, -1)] for j inrange(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]]

Or if you don't want them grouped it's simpler:

[[i>>j&1 for j in range(8*n-1, -1, -1)] for i in range(2**(8*n))]

Equivalent generator:

defbyte_array(n):
    for i inrange(2**(8*n)):
        yield [i>>j&1for j inrange(8*n-1, -1, -1)]

Post a Comment for "Python : Efficient Bytearray Incrementation"