.NET中的格雷码

tbi*_*hel 6 .net c# error-checking gray-code

在.NET框架中的任何地方都有内置的格雷码数据类型吗?或者Gray和binary之间的转换实用程序?我可以自己做,但如果轮子已经发明了......

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)