In standard binary, if you exclusive-or a number less than n**2
with n**2-1
, then you effectively reverse the order of that count:
x x^11
00 11
01 10
10 01
11 00
So, for a two-bit number, if we exclusive-or the bottom bit with the next bit:
x x^(x>>1)
00 00
01 01
10 11
11 10
We are alternately reversing the order of the count for the bottom bit, depending on whether the bit above it is set or clear. This ensures that when bit 1 changes, bit 0 stays the same (where it would otherwise have wrapped around to zero and started counting up again).
For every bit that is added at the top of the counter, we need to repeat this reflection of the count of the bit below, to ensure that it doesn't become cleared as the new bit becomes set. The remaining bits follow in the same pattern, being reflected by the bit above them such that they count backwards rather than wrapping around.