Gray Code Converter

Turn binary numbers into Gray code with n xor n>>1.

Technology and NetUpdated 2026-10-161 min read
Gray Code Converter
Gray decimal
...
Gray binary...
Binary...

What it does

Gray code orders binaries so neighbors flip one bit. Encoders use it to avoid glitches where several bits change at once. Position 10 reads 1010 binary but 1111 Gray.

The tool above takes decimal n and returns Gray decimal, Gray binary, and plain binary. The default 10 matches the worked example, so the page opens showing Gray 15. Type a new n to update all three results.

The rule is g = n xor (n>>1). For 10, binary 1010 shifted is 0101, xor is 1111 for 15. Counting Gray 0,1,3,2,6,7,5,4 shows single flips throughout.

Use Gray for rotary encoders, Karnaugh maps, and clock crossing. For error counts between codes use Hamming distance instead.

This page shows the formula, one full hand checked example at 10, a reference table, and practice checks that run through the tool.

How to use

  1. Type decimal n from 0 to 1e9.
  2. Read Gray decimal as the main result.
  3. Read Gray binary for encoder tracks.
  4. Read Binary to compare with input.
  5. Count flips between neighbors to verify.
  6. Split large ranges into chunks.

Formula

gray = n xor (n >> 1).
n
Decimal input.
>>1
Right shift one bit (halve floored).
xor
Bitwise exclusive or.

32 bit math assumed. Inputs cap at 1e9 to stay exact and fast.

Worked example

Example: n = 10

Convert decimal 10 to Gray code.

  1. Binary 10 is 1010.
  2. Shift: 1010 >> 1 = 0101 (5).
  3. XOR: 1010 xor 0101 = 1111.
  4. Decimal 1111 is 15.
  5. Tool shows Gray 15, binary 1010.
  6. Neighbor 11 gives Gray 14 (1110), one flip.

Reference table

Gray for 0 to 7
nBinaryGray
000
111
21011 (3)
7111100 (4)
1010101111 (15)

Limits

  • Nonnegative integers to 1e9 here.
  • Binary reflected Gray only.
  • No Gray to binary direction here.
  • Encoder mechanics (detents, alignment) sit outside.

Common mistakes

  • XORing decimal digits instead of bits.
  • Shifting left instead of right.
  • Expecting Gray order to match binary order.
  • Using Gray where Hamming distance is needed.
  • Running past 32 bit range.

Try it yourself

Quick checks. Answers sit tucked under each question.

Gray of 7?

Gray 4, binary 111, Gray binary 100.

Gray of 0?

Gray 0, binary 0.

Questions

10 to Gray?

15 (1111).

Why Gray?

Neighbors differ by one bit, cutting glitches.

Formula?

n xor (n>>1).

Binary?

Shown alongside for comparison.

Reverse?

Not here. Gray to binary needs a loop.

Max?

1e9 here.

Sources

How this page was checked. The formula above was matched against the cited sources, and the worked example was run through the tool on this page before publishing. If you spot an error, contact us so we can fix it and note the correction.