The neighbors in Gray code

后端 未结 3 440
梦如初夏
梦如初夏 2020-12-10 21:53

Is there any algorithm that I can use to find the neighbors in Gray code?

For small numbers is just fine to write the entire table, but if I have a number like

3条回答
  •  春和景丽
    2020-12-10 22:42

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

提交回复
热议问题