digiwleea Tools
Learn Open the lab →

Gray code converter

Convert a number to its reflected binary Gray code, or decode a Gray code value back to a number. The tool shows the per-bit XOR derivation and a run of consecutive values so you can see the whole point of Gray code: each step changes exactly one bit. For example, 5 is 0101 in binary and 0111 in Gray code.

How the conversion works

Binary to Gray is one operation: gray = n XOR (n >> 1). Read bit by bit, each Gray bit is the binary bit XORed with the binary bit to its left, and the most significant bit is copied unchanged. Going back the other way, the top binary bit equals the top Gray bit, and every lower binary bit is that Gray bit XOR the binary bit just above it, so the information ripples down from the most significant end.

Why one bit at a time

The single-bit-change property is the reason Gray code exists. In plain binary, counting from 3 (011) to 4 (100) flips all three bits at once. If those bits do not switch at exactly the same instant, a circuit reading them mid-transition can momentarily see a completely wrong value, a glitch. Gray code reorders the counts so consecutive values differ in a single bit, so there is no multi-bit transition to misread. That is why rotary and linear position encoders, and some counters, output Gray code.

Frequently asked

How do you convert binary to Gray code?

Compute n XOR (n >> 1). Each Gray bit is the binary bit XOR the binary bit to its left, with the top bit copied. For 5 (0101) you get 0111.

How do you convert Gray code back to binary?

From the top bit down: the top binary bit equals the top Gray bit, and each lower binary bit is that Gray bit XOR the binary bit above it. Equivalently, XOR-fold the Gray value with its right-shifts.

Why does Gray code change only one bit at a time?

So a circuit reading a changing value never catches a multi-bit transition mid-flight and reports a wrong number. Ordinary binary can flip several bits at once (3 to 4 flips all three); Gray code flips exactly one, which is why encoders use it.

What is 5 in Gray code?

5 is 0101 in binary and 0111 in reflected binary Gray code. Decoding 0111 as Gray gives back 5.

Gray code is one of the small encodings that make real hardware reliable. Read the Gray code lesson, or open the lab and build a counter to see multi-bit transitions for yourself.

Related tools: binary converter, bitwise calculator, and base converter.

Open the lab →

Embed this tool

Free to embed in your course page, blog, or notes: just keep the credit link under the widget. Paste this where you want it:

<iframe src="https://digiwleea.wleeaf.dev/embed/tool/?w=gray-code" width="100%" height="480" style="border:0;border-radius:12px;max-width:720px" title="Gray code converter" loading="lazy"></iframe>