Convertion of grey code and binary 格雷码和二进制数之间的转换

时间:2023-03-08 22:11:02

以下转换代码摘自* 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 >> ) ^ 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 >> ; mask != ; mask = mask >> )
{
num = num ^ mask;
}
return num;
}