Binary / Gray Code Converter

Easy · Combinational Logic

Implement an 8-bit binary-to-Gray encoder and an 8-bit Gray-to-binary decoder in one module. The two converters are independent and work at the same time.

In the (reflected binary) Gray code, consecutive numbers differ in exactly one bit. That property is why Gray-coded counters are used to pass FIFO pointers across clock domains: if a pointer is sampled while it changes, at most one bit is in flight, so the sampled value is either the old or the new value, never garbage.

Ports

PortDirWidthMeaning
bin_ininput8Unsigned binary value to encode.
gray_outoutput8Gray code of bin_in.
gray_ininput8Gray-coded value to decode.
bin_outoutput8Binary value whose Gray code is gray_in.

gray_out depends only on bin_in, and bin_out depends only on gray_in. Both are purely combinational.

Definitions

Encode (binary b → Gray g): each Gray bit is the XOR of the binary bit and the binary bit above it. The top bit is copied.

Decode (Gray g → binary b): each binary bit is the XOR of all Gray bits at or above it, which can be computed from the top down:

Decoding is the inverse of encoding: feeding gray_out back into gray_in returns bin_in on bin_out.

Examples

binary (decimal)binaryGray
00000_00000000_0000
10000_00010000_0001
20000_00100000_0011
30000_00110000_0010
40000_01000000_0110
1270111_11110100_0000
1281000_00001100_0000
2551111_11111000_0000

So bin_in = 8'd3 gives gray_out = 8'b0000_0010, and gray_in = 8'b1100_0000 gives bin_out = 8'd128.

Hint

Encoding is a one-liner with a shift and an XOR. Decoding needs a chain: in always_comb, keep a running XOR in a local variable and walk a for loop from bit 7 down to bit 0, updating the variable with gray_in[i] and copying it into bin_out[i]. (Reading bin_out[i+1] while still assigning bin_out in the same block also simulates correctly, but Verilator warns about it with ALWCOMBORDER.)

Sign up free to solve Binary / Gray Code Converter in your browser.

More Combinational Logic problems