Gray Code Converter

Convert integers to Gray code and back — single-bit transitions

Ad placeholder (leaderboard)

What this tool does

This converter translates between ordinary integers and Gray code (binary-reflected code). In Gray code, every step from one number to the next flips exactly one bit, which is why it is the standard encoding for rotary and linear position sensors, and why it makes Karnaugh-map adjacency work.

How it works

Encoding an integer n to Gray code is a one-liner:

gray = n ^ (n >> 1)

The top bit of the Gray code equals the top bit of the binary, and each lower Gray bit is the XOR of two neighbouring binary bits. That XOR is exactly what cancels out all but one bit-change between consecutive numbers.

Decoding a Gray value back to a plain integer accumulates XORs from the most-significant bit downward:

binary = gray;
while (gray >>= 1) {
  binary ^= gray;
}

Each binary bit is the running XOR of every Gray bit at or above its position.

Example

The integer 5 is 101 in binary. Its Gray code is 101 ^ 010 = 111. The integer 6 is 110, whose Gray code is 110 ^ 011 = 101 — differing from the Gray code of 5 in just one bit, which is the defining property.

Notes

  • The tool pads both the binary and Gray strings to the same width so the single-bit difference is easy to spot.
  • Decoding ignores anything that is not 0 or 1; encoding requires a non-negative decimal integer.
Ad placeholder (rectangle)