Verilog Code for Binary to Gray Converter: Simple Example
A binary to Gray code converter in
Verilog uses the formula gray = binary ^ (binary >> 1). This means each Gray code bit is the XOR of the binary bit and the bit to its right. You can implement this easily with bitwise operators in a Verilog module.Syntax
The basic syntax for a binary to Gray code converter module includes defining inputs and outputs, and using bitwise XOR and right shift operations.
- input [N-1:0] binary: The binary number input.
- output [N-1:0] gray: The Gray code output.
- assign gray = binary ^ (binary >> 1);: The conversion logic using XOR and right shift.
verilog
module binary_to_gray #(parameter N = 4) ( input wire [N-1:0] binary, output wire [N-1:0] gray ); assign gray = binary ^ (binary >> 1); endmodule
Example
This example shows a 4-bit binary to Gray code converter. It converts a binary input to its Gray code equivalent using the XOR and right shift operation.
verilog
module testbench();
reg [3:0] binary;
wire [3:0] gray;
binary_to_gray #(.N(4)) converter (
.binary(binary),
.gray(gray)
);
initial begin
$display("Binary | Gray");
for (integer i = 0; i < 16; i = i + 1) begin
binary = i;
#1; // wait for assignment
$display("%4b | %4b", binary, gray);
end
$finish;
end
endmoduleOutput
Binary | Gray
0000 | 0000
0001 | 0001
0010 | 0011
0011 | 0010
0100 | 0110
0101 | 0111
0110 | 0101
0111 | 0100
1000 | 1100
1001 | 1101
1010 | 1111
1011 | 1110
1100 | 1010
1101 | 1011
1110 | 1001
1111 | 1000
Common Pitfalls
Common mistakes include:
- Forgetting to use the right shift operator
> 1which is essential for the Gray code formula. - Using bitwise OR
|instead of XOR^. - Not parameterizing the bit width, which limits reusability.
Always verify the output matches expected Gray code values.
verilog
/* Wrong approach: Using OR instead of XOR */ module wrong_binary_to_gray( input wire [3:0] binary, output wire [3:0] gray ); assign gray = binary | (binary >> 1); // Incorrect endmodule /* Correct approach: Using XOR */ module correct_binary_to_gray( input wire [3:0] binary, output wire [3:0] gray ); assign gray = binary ^ (binary >> 1); // Correct endmodule
Quick Reference
Remember these key points for binary to Gray code conversion in Verilog:
- Use
gray = binary ^ (binary >> 1);for conversion. - Parameterize bit width for flexibility.
- Test with all input values to ensure correctness.
Key Takeaways
Use XOR between the binary number and its right-shifted version to get Gray code.
Parameterize the bit width in your Verilog module for reusable code.
Avoid using OR instead of XOR for the conversion logic.
Test your converter with all possible input values to verify correctness.
Keep the code simple and use continuous assignment for combinational logic.