generate all n bit binary numbers in a fastest way possible

ramgorur picture ramgorur · Sep 7, 2012 · Viewed 12.4k times · Source

How do I generate all possible combinations of n-bit strings? I need to generate all combinations of 20-bit strings in a fastest way possible. (my current implementation is done with bitwise AND and right shift operation, but I am looking for a faster technique).

I need to store the bit-strings in an array (or list) for the corresponding decimal numbers, like --

0 --> 0 0 0

1 --> 0 0 1

2 --> 0 1 0 ... etc.

any idea?

Answer

Tugrul Ates picture Tugrul Ates · Sep 8, 2012

Python

>> n = 3
>> l = [bin(x)[2:].rjust(n, '0') for x in range(2**n)]
>> print l
['000', '001', '010', '011', '100', '101', '110', '111']