In fact, some of the other answers seem to be wrong: it is true that the two binary reflected binary code of the Gray code differs by only one bit (I assume that by using the "gray" sequence of Gray code you mean the original binary reflected code sequence of Gray, as described by Frank Gray). However, this does not mean that two Gray codes that differ by one bit are neighbors ( a => b does not mean that b => a ). For example, the codes Gray 1000 and 1010 differ by only one bit, but are not neighbors (1000 and 1010 are respectively 15 and 12 in decimal form).
If you want to know if the two gray codes a and b neighbors, you should check if previous(a) = b OR next(a) = b . For a given Gray code, you get one neighbor by flipping the rightmost bit and another neighbor bit by flipping the bit to the left of the rightmost set bit. For gray code 1010, neighbors are 1011 and 1110 (1000 is not one of them).
Whether you get the previous or next neighbor by flipping one of these bits actually depends on the parity of the Gray code. However, since we want both neighbors, we do not need to parity. The following pseudo code should tell you if two Gray codes are neighbors (using C-like bitwise operations):
function are_gray_neighbours(a: gray, b: gray) -> boolean return b = a ^ 1 OR b = a ^ ((a & -a) << 1) end
Bit trick above: a & -a isolates a fixed-set bit quantity. We shift this bit one position to the left to get the bit that we need to flip.
source share