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 system | Binary System | Gray Code |
---|---|---|
0 | 0000 | 0000 |
1 | 0001 | 0001 |
2 | 0010 | 0011 |
3 | 0011 | 0010 |
4 | 0100 | 0110 |
5 | 0101 | 0111 |
6 | 0110 | 0101 |
7 | 0111 | 0100 |
8 | 1000 | 1100 |
9 | 1001 | 1101 |
10 | 1010 | 1111 |
11 | 1011 | 1110 |
12 | 1100 | 1010 |
13 | 1101 | 1011 |
14 | 1110 | 1001 |
15 | 1111 | 1000 |