Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate all n bit binary numbers in a fastest way possible

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?

like image 528
ramgorur Avatar asked Nov 02 '25 03:11

ramgorur


1 Answers

Python

>>> n = 3
>>> for x in range(2**n):
...   print(f'{x:0{n}b}')
...
000
001
010
011
100
101
110
111
like image 91
Tugrul Ates Avatar answered Nov 04 '25 14:11

Tugrul Ates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!