Gray code (reflected binary code) is a binary numeral system where consecutive values differ by exactly one bit. This is critical in digital engineering — encoders, ADCs, and rotating position sensors use Gray code to prevent transient multi-bit errors when reading a mechanical shaft position that sits between two code states. This converter translates between binary and Gray code in both directions.
In a standard binary counter, changing from 0111 (7) to 1000 (8) requires flipping all four bits simultaneously. In physical hardware, this never happens perfectly — for a brief moment you might read 0110, 1010, or any intermediate state. In Gray code, the same transition is 0100 → 1100 — only one bit flips, eliminating the ambiguity. This property makes Gray code essential in shaft encoders, analog-to-digital conversion, and error-correction in communications.
The most significant bit stays the same. Each subsequent bit is XOR'd with the previous binary bit: G[i] = B[i] XOR B[i-1]. Example: binary 1011 → Gray: 1=1, 1 XOR 0=1, 0 XOR 1=1, 1 XOR 1=0 → Gray = 1110.
The MSB stays. Each subsequent binary bit is XOR'd with the previous binary bit (not Gray bit): B[i] = G[i] XOR B[i-1]. The process works left to right.
Frank Gray patented the reflected binary code in 1953 while working at Bell Labs. The "reflected" name comes from the construction method: the sequence is built by taking the n-bit code and appending its mirror image with a leading 1-bit added.
Gray code sequences appear in Hamiltonian paths on hypercube graphs, in puzzles like the Tower of Hanoi (the solution sequence corresponds to Gray code), and in minimising logic expressions using Karnaugh maps.
See also Binary to Decimal, BCD Converter, and the Bitwise Calculator.