I know this is an old topic, but I came across the same question and I found a little trick. If you have bit n , instead of having to perform n bits operations (for example, Jesper's answer), you can do this with log2 (n) number :
Assuming y is equal to x XOR (x / 2) at the beginning of the program, you can execute the following C program:
INPUT : y int i, x; x = y; for (i = 1; i < n; i <<= 1) x ^= x >> i; OUTPUT : x
and here you have a solution.
- "β" - operation of the right shift of bits. For example, the number 13, 1101 in binary, if it is shifted by 1 on the right, will become 110 in binary, so 13 β 1 = 6. x β i is equivalent to x / 2 ^ i (division by integers, of course)
- "<<" - operation to shift the left bit (i <= 1 is equivalent to i * = 2)
Why does this work? Take n = 5 bits as an example and start with y = b4 b3 b2 b1 b0 (in binary format: in the next x is also written in binary, but I am written in decimal)
x = b4 b3 b2 b1 b0
x β 1 = b4 b3 b2 b1, so we have (b2 ^ b3) (b1 ^ b2) (b0 ^ b1)
x β 2 = b4 (b3 ^ b4) (b2 ^ b3), so we have x = b4 (b3 ^ b4) (b2 ^ b3) (b1 ^ b2) (b0 ^ b1) XOR b4 (b3 ^ b4) (b2 ^ b3) = b4 (b3 ^ b4) (b2 ^ b3 ^ b4) (b1 ^ b2 ^ b3 ^ b4) (b0 ^ b1 ^ b2 ^ b3)
x β 4 = b4, so we have x = b4 (b3 ^ b4) (b2 ^ b3 ^ b4) (b1 ^ b2 ^ b3 ^ b4) (b0 ^ b1 ^ b2 ^ b3) XOR b4 = b4 (b3 ^ b4 ) (b2 ^ b3 ^ b4) (b1 ^ b2 ^ b3 ^ b4) (b0 ^ b1 ^ b2 ^ b3 ^ b4)
- Then I = 8, which is more than 5, we exit the cycle.
And we have the desired result.
There are log2 (n) iterations in the loop, because I start with 1 and multiply by 2 at each step, so in order for me to reach n, we have to do it log2 (n) times.
Yann
source share