I am trying to find an algorithm to count from 0 to 2n-1 but their bit pattern reversed. I care about only n LSB of a word. As you may have guessed I failed.
For n=3:
000 -> 0 100 -> 4 010 -> 2 110 -> 6 001 -> 1 101 -> 5 011 -> 3 111 -> 7
You get the idea.
Answers in pseudo-code is great. Code fragments in any language are welcome, answers without bit operations are preferred.
Please don’t just post a fragment without even a short explanation or a pointer to a source.
Edit: I forgot to add, I already have a naive implementation which just bit-reverses a count variable. In a sense, this method is not really counting.
This is, I think easiest with bit operations, even though you said this wasn’t preferred
Assuming 32 bit ints, here’s a nifty chunk of code that can reverse all of the bits without doing it in 32 steps:
Essentially this does an interleaved shuffle of all of the bits. Each time around half of the bits in the value are swapped with the other half.
The last line is necessary to realign the bits so that bin ‘n’ is the most significant bit.
Shorter versions of this are possible if ‘n’ is <= 16, or <= 8