Binary to Gray Code Converter
Convert binary numbers to Gray code and back instantly. Supports batch conversion, step-by-step XOR visualization, and bit grouping for digital circuit design.
About
Gray code (reflected binary code) changes only one bit between successive values. This property eliminates transition glitches in rotary encoders, ADCs, and Karnaugh maps where multiple simultaneous bit flips cause spurious intermediate states. A standard binary counter transitioning from 0111 to 1000 flips all four bits. If hardware latches read mid-transition, the sampled value could be any of 16 states. Gray code guarantees exactly one bit changes per step, removing that race condition entirely.
This converter implements the canonical XOR algorithm: the Gray code bit gi equals bi ⊕ bi−1 for each position after the MSB. It handles arbitrary bit widths up to 64 bits. Note: this tool works with unsigned integers only. Gray code has no inherent sign representation, so negative values require a separate encoding convention such as offset binary before conversion.
Formulas
Binary to Gray code conversion operates bitwise. The most significant bit (MSB) of the Gray code equals the MSB of the binary input. Every subsequent Gray bit is derived by XOR of the current binary bit with its left neighbor.
The reverse (Gray to Binary) reconstructs each binary bit by XOR of the Gray bit with the previously decoded binary bit:
Where bi is the i-th binary bit (index 0 = MSB), gi is the i-th Gray code bit, ⊕ denotes exclusive OR (XOR), and n is the total bit count. The Hamming distance between any two consecutive Gray code values is always exactly 1.
Reference Data
| Decimal | Binary | Gray Code | Hamming Distance |
|---|---|---|---|
| 0 | 0000 | 0000 | 0 |
| 1 | 0001 | 0001 | 1 |
| 2 | 0010 | 0011 | 1 |
| 3 | 0011 | 0010 | 1 |
| 4 | 0100 | 0110 | 1 |
| 5 | 0101 | 0111 | 1 |
| 6 | 0110 | 0101 | 1 |
| 7 | 0111 | 0100 | 1 |
| 8 | 1000 | 1100 | 1 |
| 9 | 1001 | 1101 | 1 |
| 10 | 1010 | 1111 | 1 |
| 11 | 1011 | 1110 | 1 |
| 12 | 1100 | 1010 | 1 |
| 13 | 1101 | 1011 | 1 |
| 14 | 1110 | 1001 | 1 |
| 15 | 1111 | 1000 | 1 |
| 16 | 10000 | 11000 | 1 |
| 17 | 10001 | 11001 | 1 |
| 18 | 10010 | 11011 | 1 |
| 19 | 10011 | 11010 | 1 |
| 20 | 10100 | 11110 | 1 |
| 21 | 10101 | 11111 | 1 |
| 22 | 10110 | 11101 | 1 |
| 23 | 10111 | 11100 | 1 |
| 24 | 11000 | 10100 | 1 |
| 25 | 11001 | 10101 | 1 |
| 26 | 11010 | 10111 | 1 |
| 27 | 11011 | 10110 | 1 |
| 28 | 11100 | 10010 | 1 |
| 29 | 11101 | 10011 | 1 |
| 30 | 11110 | 10001 | 1 |
| 31 | 11111 | 10000 | 1 |