1. 程式人生 > >Convertion of grey code and binary 格雷碼和二進位制數之間的轉換

Convertion of grey code and binary 格雷碼和二進位制數之間的轉換

以下轉換程式碼摘自維基百科 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; }