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?
An
unsigned longis a sequence of bits.If what you want is a string of characters
'0'and'1', then you could convertito that format each time. You might be able to get a speed-up taking advantage of the fact that consecutive numbers normally share a long initial substring. So you could do something like this:I’ve only increased from 1 loop to 2 there, but I do a little over 50% as much converting from bits to chars as before. You could experiment with the following:
'0', change it to a'1', and change all the'1's after it to'0'.To fiendishly optimize
write_bitstring, multiples of 4 are good because on most architectures you can blit 4 characters at a time in a word write:To start:
Function definition:
I haven’t tested any of this: obviously you’re responsible for writing a benchmark that you can use to experiment.