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;
}