Comparator
Compare the same bit patterns for equality and magnitude. In four bits, 1111 is above 0001 under unsigned interpretation and below it under signed interpretation. For mixed types, check how the operands are extended before interpreting the result.
The collector compares reading A with threshold B. A is 1111 and B is 0001. With unsigned readings, A means fifteen and is greater. With two’s-complement calibration values, A means minus one and is less than B.
Equality checks the bits. Ordering uses the numeric interpretation
The outputs lt, eq, and gt mean less than, equal to, and greater than. For equal-width binary inputs, equality checks whether the patterns match. For ordering, decide whether the high bit is a sign bit. signed_mode=0 uses unsigned comparison. signed_mode=1 casts both operands to signed values of the same width with $signed. Their bits stay the same and their interpretation changes.
Widen signed 1111 to eight bits by repeating the sign bit. 11111111 still means −1. To keep unsigned fifteen, zero-extend it to 00001111. Mixing signed and unsigned operands can cause an unsigned comparison. Make their widths and types explicit before comparing.
Synthesizable SystemVerilog
module comparator4 (
input logic [3:0] a,
input logic [3:0] b,
input logic signed_mode,
output logic lt,
output logic eq,
output logic gt
);
assign lt = signed_mode ? ($signed(a) < $signed(b)) : (a < b);
assign eq = a == b;
assign gt = signed_mode ? ($signed(a) > $signed(b)) : (a > b);
endmodule
Check the results against the waveform
Data values are hexadecimal. Control signals and flags are shown separately.
| Change at | a | b | signed_mode | lt | eq | gt |
|---|---|---|---|---|---|---|
| 0 ns | F | 1 | 0 | 0 | 0 | 1 |
| 10 ns | F | 1 | 1 | 1 | 0 | 0 |
| 20 ns | F | F | 1 | 0 | 1 | 0 |
| 30 ns | 8 | 7 | 1 | 1 | 0 | 0 |
| 40 ns | 8 | 7 | 0 | 0 | 0 | 1 |
When both inputs are F, either mode gives eq=1. Compare F with 1 to expose a wrong mode. The lt and gt flags swap.
Download the runnable SystemVerilog lab. Icarus checks the 5 rows above and 512 binary input combinations. It reads each directed result 1 ns after changing the inputs. The wait sets an observation time in the testbench. The waveform is functional evidence. Physical delay needs a timing model.
Interactive lab
Keep A=F and B=1 and switch signed mode to swap lt and gt. Set both inputs to F to check equality.
- Less than lt
- Equal eq
- Greater than gt
Show the last eight observations
Teaching film
Run the RTL yourself
Extract the lab and follow the commands in its README. Compare the simulated outputs and waveform with your predictions from the interactive lab.
Download Comparator RTL (.zip)