SourceRTL Design Directory

Code Converter: Binary to/from Gray Code

Code converters are digital circuits that convert data from one form of binary representation to another. The two most important code converts are binary to gray and gray to binary. This converters are crucial digital components in designing [Aysnchronous FIFO].

Binary Code

Binary code is a data representation system using only two states, zero (0) and one (1). Each digit is represented by the power of 2 with the starting bit as 2^0 and 2^1 and so on. Binary code is basic is the fundamental numerical representation in computer systems.

Verilog Code: Binary to Gray

To convert a binary number to its corresponding Gray code, you can use the following formula:

gray_num[i] = binary_num[i] xor binary_num[i+1]

assign bin_2_gray = (bin >> 1) ^ bin;

Gray Code

Gray code is representation of a binary system where two successive values differ only by one bit. This property is crucial is digital system in minimizing errors.

Verilog Code: Gray to Binary

To convert a binary number to its corresponding Gray code, you can use the following formula:

bin[0] = gray[3] ^ gray[2] ^ gray[1] ^ gray[0] ; // gray>>0

bin[1] = 1’b0 ^ gray[3] ^ gray[2] ^ gray[1] ; // gray>>1

bin[2] = 1’b0 ^ 1’b0 ^ gray[3] ^ gray[2] ; // gray>>2

bin[3] = 1’b0 ^ 1’b0 ^ 1’b0 ^ gray[3] ; // gray>>3

integer i;
   always@(*) begin
      for(i=0; i<n ; i=i+1)  // n = width of the data
               gray_2_bin[i] = ^(bin_2_gray >> i);
   end

Truth Table

The turth table represents the convertion of 4-bit binary code to gray code.

Decimal systemBinary SystemGray Code
000000000
100010001
200100011
300110010
401000110
501010111
601100101
701110100
810001100
910011101
1010101111
1110111110
1211001010
1311011011
1411101001
1511111000

Reference

  1. Synthesis and Scripting Techniques for Designing Multi-Asynchronous Clock Designs