Gray-code converter

Count so that only one bit ever changes at a time.

When to use it

In Gray code, consecutive values differ in exactly one bit. That's gold for crossing clock domains: if you sample a Gray-coded counter mid-transition you can only ever read the old or the new value, never a garbage in-between, so it's how async FIFO pointers are carried across.

How it works

Binary to Gray is a single row of XORs: g = b ^ (b >> 1). Gray back to binary is a running (prefix) XOR from the top bit down. Both are cheap, unclocked logic.

Gotchas

Try it

Runs on our simulator, edit the code and press Run to see the waveform.

Open & fork in the playground → Ship the verified version: lfpga add lfpga_gray

The runnable example above is a teaching version. The libfpga library ships a hardened, parameterised, CI-tested module (lfpga_gray) for production use.

Next recipe: SPI master