Gray code converter

Binary to Gray code (b XOR b shifted right) and back with a prefix XOR, and the table of all n-bit codes.

How it works

In the Gray code (the reflected binary code, patented by Frank Gray in 1953) two consecutive numbers always differ in exactly one bit: 0, 1, 3, 2, 6, 7, 5, 4 in 3 bits is 000, 001, 011, 010, 110, 111, 101, 100. Ordinary binary does not have this property: going from 3 to 4 (011 to 100) flips all three bits.

The conversion is one XOR: $g = b \oplus (b \gg 1)$, so each Gray bit says whether a binary bit differs from its left neighbour. Going back, the top bit stays, and each further binary bit is the XOR of all Gray bits above and including it, a prefix XOR.

Gray codes are used where a reading may be taken while bits are changing, as in rotary and position encoders: a misread can only be off by one step. They also order the cells of Karnaugh maps and appear in genetic algorithms and error correction.

Everything is calculated in your browser. Nothing you type leaves your device.