在灰色code的邻居 [英] The neighbors in Gray code
本文介绍了在灰色code的邻居的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有什么算法,我可以用它来查找灰色code邻居?
Is there any algorithm that I can use to find the neighbors in Gray code?
有关小数目是蛮好写的整个表,但如果我有一些类似的 010 110 是有点多用6个号码写入整个灰色code表。
For small numbers is just fine to write the entire table, but if I have a number like 010 110 is a bit to much to write the entire grey code table with 6 numbers.
推荐答案
从的维基百科:
/*
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;
}
和现在,所需的code,使用该掩模对位的数目限制为6:
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);
}
这篇关于在灰色code的邻居的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文