๐ฒ Gray Code Converter
Convert a binary number to standard reflected binary Gray code, or convert Gray code back to binary. Gray code has the property that adjacent values differ by only one bit, which is used in rotary encoders and digital circuits to prevent errors.
How to use
- Choose "binary to Gray" or "Gray to binary" mode.
- Enter a bit string made of 0s and 1s.
- The converted value and its decimal equivalent are shown automatically.
How the calculation works
Gray code (reflected binary code) is an ordering of binary numbers in which consecutive values differ in exactly one bit. It is named after Frank Gray, who patented it in 1953. Binary to Gray: XOR the number with itself shifted right by one bit. Gray = n XOR (n >> 1) Gray to binary: XOR together the Gray code shifted right by 0, 1, 2 โฆ bits. In ordinary binary, going from 3 (011) to 4 (100) flips three bits at once, so a reading taken mid-change can briefly show a completely wrong value. Gray code only ever changes one bit, so this cannot happen. The tool handles up to 32 bits.
Worked example
Gray code for 0โ7 (3 bits) 0 โ 000 1 โ 001 2 โ 011 3 โ 010 4 โ 110 5 โ 111 6 โ 101 7 โ 100 Binary 101 (5) โ 101 XOR 010 = 111 Gray 111 converts back to 101 (5)
Things to be aware of
- Used in rotary encoders that read shaft angles and in Karnaugh maps for simplifying logic circuits.
- Going from the last value (7 = 100) back to the first (0 = 000) also changes only one bit, which suits things that wrap around.
- Input is a string of 0s and 1s, and the output uses the same number of bits as the input.
FAQ
What is Gray code?
Itโs a standard bit representation called reflected binary code, where adjacent values differ by exactly one bit. Itโs used in rotary encoders, Karnaugh maps, and similar applications.
What formula does this use?
Binary to Gray uses gray = binary XOR (binary >> 1). The reverse conversion iteratively XOR-folds the Gray code bits from the most significant bit down, the standard method.
What does the 3-bit Gray code sequence look like?
It goes 000, 001, 011, 010, 110, 111, 101, 100 โ the standard reflected binary sequence.