Gray code in one minute
Gray code (reflected binary code) is a binary numbering system in which any two consecutive numbers differ in exactly one bit. That single-bit-change property is what makes it valuable for rotary encoders, Karnaugh maps, and digital communications where a transient misread should never cause a large jump in the decoded value.
How it works
To convert a binary number to Gray code, XOR the number with itself shifted one position to the right:
gray = n ^ (n >> 1)
The most significant bit is always copied unchanged; every other Gray bit is the XOR of the current binary bit and the bit immediately to its left.
Decoding reverses the process by accumulating XORs from the top bit down:
binary[0] = gray[0]
binary[i] = binary[i-1] ^ gray[i]
This converter applies these exact operations, so the encoded and decoded results are always bit-accurate for any non-negative integer within the safe integer range.
Example and tips
Decimal 4 is 100 in binary. Its Gray code is 100 ^ 010 = 110, which is
decimal 6 when read as plain binary. Notice that the value 4 and its
neighbour 5 (Gray 111) differ in only one bit — exactly the guarantee Gray
code provides. When entering binary strings, leading zeros are preserved in the
display so you can line up the bit columns for teaching or debugging.