I need a function that returns a number essentially telling me which bit would be the one to flip when moving to the nth element of a Gray code. It doesn't matter if it's the standard (reflecting) Gray code or some other minimal bit-toggling approach. I can do it, but it seems unnecessarily unwieldy. Currently I have this:
#include <stdio.h>
int main()
{
int i;
for (i=1; i<32; i++)
printf("%d\n",grayBitToFlip(i));
}
int grayBitToFlip(int n)
{
int j, d, n1, n2;
n1 = (n-1)^((n-1)>>1);
n2 = n^(n>>1);
d = n1^n2;
j = 0;
while (d >>= 1)
j++;
return j;
}
The loop in main() is only there to demonstrate the output of the function.
Is there a better way?
EDIT: just looking at the output, it's obvious one can do this more simply. I've added a 2nd function, gray2, that does the same thing much more simply. Would this be the way to do it? This is not production code by the way but hobbyist.
#include <stdio.h>
int main()
{
int i;
for (i=1; i<32; i++)
printf("%d %d\n",grayBitToFlip(i), gray2(i));
}
int grayBitToFlip(int n)
{
int j, d, n1, n2;
n1 = (n-1)^((n-1)>>1);
n2 = n^(n>>1);
d = n1^n2;
j = 0;
while (d >>= 1)
j++;
return j;
}
int gray2(int n)
{
int j;
j=0;
while (n)
{
if (n & 1)
return j;
n >>= 1;
j++;
}
return j;
}
1bit. The way to test a gray-code generator is to flip the bit, and then feed the resulting value into the generator. For example, starting with binary0000, the bit to flip is 0, so the new value is0001. Give that to the generator and the bit to flip is 0 again. So the value toggles between0000and0001. As another example, start with1111and the sequence generated is1110,1100,1000,0000,0001,0000,0001, ... That's not a gray code.nisn&-n. If your time intent is to flip the bit, that is what you need. (But I guessnneeds to start at 1.) If you need the index of the bit, you can use a clz instruction. See theffsfunction.