Gray Code Converter

Binary to Gray code and back, step by step.

  • Any bit width
  • Full sequence table
  • Which bit flips
A loop of cream and grey soft clay segments laid in a ring around a short rounded post on a sandy surface.

The guide

One bit at a time: why a Gray code keeps a turning sensor honest

The reflected binary code orders every number so that neighbours differ in a single bit, which is why shaft encoders, and one old puzzle, still use it.

  • 1 bit changes between any two neighbouring Gray codes
  • 1953 year Frank Gray's patent for the code was published
  • 239 decimal reading of the Gray code of 181, which is 11101111
  • 0 1 0 2 bit that changes at steps 1 to 4, a ruler pattern
Read the full guide Fold the guide 7 min · 11 sources

Count from 1 to 2 in ordinary binary and two bits change at once: 001 becomes 010. On paper that is nothing. On a machine that reads each bit from a separate wire or track, it is a hazard, because the two changes never land at exactly the same instant.

For a moment the reader can see 011 or 000, a position that was never visited. Nothing in the data says the reading is wrong. The Gray code exists to remove that moment, and it does so by a rule so small that it fits in one line of arithmetic.

What one bit buys you

A Gray code is an ordering of the binary numbers in which any two neighbours differ in exactly one bit. In the version this page uses, the reflected binary code, 1 becomes 001 and 2 becomes 011, so stepping from one to the other flips a single bit. The Wikipedia article on the code states the idea this plainly, and adds that it is widely used to prevent spurious output from electromechanical switches.

Position sensors are the classic customer. A rotary encoder reads a disk with concentric tracks, one track per bit, and the pattern under the sensors names the angle. If the pattern is plain binary, a sensor that is slightly early or late can report a position far from the true one. With a Gray pattern, only one track changes at each boundary, so the worst misreading is the neighbouring position.

The United States Department of Defense handbook on shaft angle encoders makes the same argument in its own terms. It calls the code a unit distance code, says that because only one bit changes it is impossible to generate erroneous data at a transition, and notes that with a cam arrangement of this kind the alignment of the cams is much less critical, since only one switch changes at a time.

That is a practical benefit with a mechanical meaning. Looser alignment, simpler adjustment, and an error that is bounded rather than wild. It also explains the name: Frank Gray at Bell Telephone Laboratories filed a patent application in November 1947 for pulse code communication, and the patent, published in 1953, calls the code the reflected binary code, adding that it has as yet no recognized name. The article on the code also credits George Stibitz of the same laboratories with an earlier patent on such a code.

Building it by reflection

The patent’s name for the code describes how to build it. Start with the list for one bit: 0, 1. To get the list for two bits, write the one-bit list, then write it again in reverse order, and put a 0 in front of the first copy and a 1 in front of the second. That gives 00, 01, 11, 10.

Do it again for three bits. The two-bit list reversed is 10, 11, 01, 00. Prefix the original with 0 and the reversed copy with 1, and join them: 000, 001, 011, 010, 110, 111, 101, 100. The four-bit list continues the same way and ends with 1010, 1011, 1001, 1000. Each list is the first half of the next one, so a number keeps its code as the width grows.

Three properties follow straight from the construction. Every number appears exactly once, so the list is a permutation of the numbers. Neighbours differ by 1 bit, because inside each half they did already and at the seam the two entries are mirror images that share every bit except the new prefix. And the last entry differs from the first by one bit as well, so the code is a loop, not just a line.

The loop has a pretty reading. Walking a Gray code of n bits visits every corner of an n-dimensional cube exactly once and returns to the start, moving along an edge at each step. The Wikipedia article describes this as a cycle through a hypercube graph.

One line of arithmetic, in both directions

Building a list of a million entries by reflection is fine, but converting a single number should not need a list. The shortcut is to take the number and XOR it with itself shifted right by one place. The Gray code of 5 is 5 XOR 2, which is 111 XOR 010, which is 111 read as 7; the sequence listed in the Encyclopedia of Integer Sequences as the decimal values of the Gray codes begins 0, 1, 3, 2, 6, 7, 5, 4, and its stated formula is exactly this XOR.

Why does the shortcut agree with the reflection? Look at one bit. In the list, a bit is inverted whenever the next higher bit of the number is 1, and left alone when it is 0. Putting a 1 in front of a list reverses its order, and inverting a lower bit reverses blocks of neighbouring entries in the same way. The XOR of each bit with the bit above it performs just this reversal in every block at once.

The way back is where people trip. The inverse is not a single XOR with the shifted code. Each number bit depends on the one above it that you have already worked out: the top bit is copied, and every bit below is the Gray bit XOR the number bit just above. Written as a prefix sum, it is a running XOR down the whole code.

Take 1100. The top bit stays 1. The next is 1 XOR 1, which is 0. The next is 0 XOR 0, which is 0, and the last is 0 XOR 0, which is 0. The number is 1000, which is 8. A shortcut that XORs once with a shifted copy would say 1010, which is 10, and would be wrong. The handbook adds a hardware note: a translation of this kind can be done serially, starting from the most significant digit in one word time, or from the least significant digit in two word times.

A worked example, and the Hanoi ruler

Try 181, which is 10110101 in binary. Shifted right by one it is 01011010. XOR the two rows bit by bit and you get 11101111, a Gray code whose decimal reading is 239. Check the single-step property by hand if you like: the code of 180 is 11101110 and the code of 182 is 11101101, and each differs from 11101111 in 1 bit. Now decode 11101111 with the running XOR: 1, then 1 XOR 1 is 0, then 0 XOR 1 is 1, then 1 XOR 0 is 1, and so on down to 10110101, which is 181 again. Everything here can be reproduced in the converter, which prints the XOR for every bit.

Now look at which bit changes from one step to the next in the whole list. Between steps 0 and 1 it is bit 0, counting from the right. Between 1 and 2 it is bit 1. Then 0, then 2, then 0, 1, 0, 3, and so on: the pattern 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 4. The bit that changes at step n is the position of the lowest 1 in n, the sequence the Encyclopedia of Integer Sequences calls the ruler function.

The same pattern runs the Tower of Hanoi. In the optimal solution, the disk moved at step n is the one numbered by that ruler value plus one, so disk 1 moves on every odd step, disk 2 on every fourth step starting at step 2, and so on. The sequence entry says so directly: it is the number of the disk to be moved at step n, and equally which bit to flip when building the reflected code. The Wikipedia article adds that the code can serve as a solution guide for the puzzle, and describes the solving scheme of the older Chinese rings puzzle as a Gray code too.

The converter lets you watch the link. Pick three disks, and the move list reads 1, 2, 1, 3, 1, 2, 1. The Gray code of each step differs from the previous by that disk’s bit. A solution made by ordinary recursion, with the pegs tracked, agrees with the lowest-set-bit rule for all 255 moves of an 8-disk tower.

What the tool does with big numbers, and what it leaves out

Ordinary JavaScript numbers lose exact whole-number precision above 2 to the power 53 minus 1, so the page holds values as BigInt. MDN states that BigInt supports the XOR and right-shift operators, and shows exact arithmetic past that limit. That lets a 41-digit number, or a 4,096-bit one, round-trip through both directions without a rounding error.

Negative numbers are refused with a plain message. A BigInt right shift copies the sign, and Python describes its bit operations as acting on a two’s complement number with an endless string of sign bits. A negative number has no fixed width in which its Gray code is a finite pattern, so the page asks for zero or a positive number instead of picking a width for you.

The heavy checks run in a worker, a background thread that exchanges messages with the page, so typing stays smooth. They cover every 16-bit round trip, the single-step property for every code below 2 to the power 20, and the ruler pattern for every step below 16,384. They test the page’s own rules, and they do not replace reading the sources.

There are limits to state. This is the reflected binary code only. Balanced Gray codes, codes in bases other than two, and codes that skip values are different constructions that this page does not generate. It does not design encoder hardware, choose a disk resolution or add error correction. If a sensor needs a particular track layout, that decision belongs to its maker’s documentation, which this page does not replace.

What the page does well is small and exact: convert in either direction, show every XOR, list the whole sequence up to 10 bits, and check on every row that neighbours differ in exactly one bit, wrap-around included. If a list you found elsewhere is not reflected, or drops leading zeros, those checks will show it.

Sources

Every source consulted for this guide. Links checked November 10, 2026.

  1. Gray code Wikipedia
  2. MIL-HDBK-231A: Military Handbook, Encoders, Shaft Angle to Digital United States Department of Defense (Internet Archive copy)
  3. US2632058A: Pulse code communication Google Patents (inventor Frank Gray, Bell Telephone Laboratories)
  4. A003188: Decimal equivalent of Gray code for n The On-Line Encyclopedia of Integer Sequences
  5. A006068: a(n) is Gray-coded into n The On-Line Encyclopedia of Integer Sequences
  6. A001511: The ruler function The On-Line Encyclopedia of Integer Sequences
  7. BigInt - JavaScript MDN Web Docs
  8. Bitwise XOR (^) - JavaScript MDN Web Docs
  9. Right shift (>>) - JavaScript MDN Web Docs
  10. Web Workers API - Web APIs MDN Web Docs
  11. Built-in Types (Python documentation) Python Software Foundation