Art*_*ius 13
使用这个技巧.
/*
The purpose of this function is to convert an unsigned
binary number to reflected binary Gray code.
*/
unsigned short binaryToGray(unsigned short num)
{
return (num>>1) ^ num;
}
Run Code Online (Sandbox Code Playgroud)
一个棘手的技巧:对于最多2 ^ n位,您可以通过执行(2 ^ n) - 1二进制到格雷转换将灰度转换为二进制.您只需要上面的函数和'for'循环.
/*
The purpose of this function is to convert a reflected binary
Gray code number to a binary number.
*/
unsigned short grayToBinary(unsigned short num)
{
unsigned short temp = num ^ (num>>8);
temp ^= (temp>>4);
temp ^= (temp>>2);
temp ^= (temp>>1);
return temp;
}
Run Code Online (Sandbox Code Playgroud)