Designing Comparators in Verilog and SystemVerilog
Comparators are digital circuits that compare two input values and produce a signal indicating whether the two values are equal or not. In this tutorial, we will use Verilog and SystemVerilog to design a 4-bit unsigned comparator and a 4-bit signed comparator.
Designing an Unsigned Comparator in Verilog and SystemVerilog
An unsigned comparator compares the magnitude of two unsigned numbers. In this implementation, we use the >
and <
operators to compare two 4-bit unsigned inputs.
module UnsignedComparator (
input logic [3:0] a,
input logic [3:0] b,
output logic gt,
output logic lt,
output logic eq
);
assign gt = (a > b) ? 1'b1 : 1'b0;
assign lt = (a < b) ? 1'b1 : 1'b0;
assign eq = (a == b) ? 1'b1 : 1'b0;
endmodule
The UnsignedComparator module has the following ports:
a
: the first 4-bit inputb
: the second 4-bit inputgt
: the output signal indicating whether a is greater than b (1) or not (0)lt
: the output signal indicating whether a is less than b (1) or not (0)eq
: the output signal indicating whether a is equal to b (1) or not (0)
Designing a Signed Comparator in Verilog and SystemVerilog
A signed comparator compares the values of two signed numbers. In this implementation, we use the $signed
function to convert the inputs to signed values, and then use the >
and <
operators to compare them.
module SignedComparator (
input logic [3:0] a,
input logic [3:0] b,
output logic gt,
output logic lt,
output logic eq
);
assign gt = ($signed(a) > $signed(b)) ? 1'b1 : 1'b0;
assign lt = ($signed(a) < $signed(b)) ? 1'b1 : 1'b0;
assign eq = (a == b) ? 1'b1 : 1'b0;
endmodule
The SignedComparator module has the following ports:
a
: the first 4-bit inputb
: the second 4-bit inputgt
: the output signal indicating whether a is greater than b (1) or not (0)lt
: the output signal indicating whether a is less than b (1) or not (0)eq
: the output signal indicating whether a is equal to b (1) or not (0)
In the SignedComparator module, we use the $signed
function to convert the inputs a
and b
to signed values, which allows us to compare them using the >
and <
operators. We also added a simple equality check using the ==
operator to output the signal eq
. If the inputs a
and b
are equal, the signal eq
will be asserted.
This implementation can be easily extended to larger input sizes by increasing the bit width of the input ports a
and b
.
Conclusion
In this tutorial, we designed two different comparators in Verilog and SystemVerilog: a 4-bit unsigned comparator and a 4-bit signed comparator. Comparators are widely used in digital circuits for comparing inputs and making decisions based on the result. The comparators we designed can be used as building blocks for more complex digital circuits, such as processors and memory systems.