Copied shamelessly from Wikipedia:
/*
The purpose of this function is to convert an unsigned
binary number to reflected binary Gray code.
The operator >> is shift right. The operator ^ is exclusive or.
*/
unsigned int binaryToGray(unsigned int num)
{
return (num >> 1) ^ num;
}
/*
The purpose of this function is to convert a reflected binary
Gray code number to a binary number.
*/
unsigned int grayToBinary(unsigned int num)
{
unsigned int mask;
for (mask = num >> 1; mask != 0; mask = mask >> 1)
{
num = num ^ mask;
}
return num;
}
And now, the requested code, using the mask to limit the number of bits to 6:
unsigned int nextGray(unsigned int num)
{
return binaryToGray((grayToBinary(num) + 1) & 0x3F);
}
unsigned int prevGray(unsigned int num)
{
return binaryToGray((grayToBinary(num) - 1) & 0x3F);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…