gray-code

The neighbors in Gray code

∥☆過路亽.° 提交于 2019-11-27 06:29:07
问题 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 010 110 is a bit to much to write the entire grey code table with 6 numbers. 回答1: 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) {

the nth gray code

半城伤御伤魂 提交于 2019-11-27 02:22:38
问题 the formula for calculating nth gray code is : (n-1) XOR (floor((n-1)/2)) (Source: wikipedia) I encoded it as: int gray(int n) { n--; return n ^ (n >> 1); } Can someone explain how the above formula works, or possibly its deriviation? 回答1: If you look at binary counting sequence, you note, that neighboring codes differ at several last bits (with no holes), so if you xor them, pattern of several trailing 1's appear. Also, when you shift numbers right, xors also will be shifted right: (A xor B)