Gray code in .NET

后端 未结 5 1901
忘掉有多难
忘掉有多难 2021-01-03 01:05

Is there a built in Gray code datatype anywhere in the .NET framework? Or conversion utility between Gray and binary? I could do it myself, but if the wheel has already be

5条回答
  •  孤独总比滥情好
    2021-01-03 01:16

    Use this trick.

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

    A tricky Trick: for up to 2^n bits, you can convert Gray to binary by performing (2^n) - 1 binary-to Gray conversions. All you need is the function above and a 'for' loop.

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

提交回复
热议问题