8 bit Magnitude Comparator

  1. Introduction


    An 8-bit magnitude comparator compares the two 8-bit values and produce a 1-bit flag as result, which indicates that the first value is either greater than or less than or equal to the second value. The block diagram of a comparator is shown in Figure 1. One key point to note is that Verilog treats reg data type as unsigned integer number of specified width. Therefore, the comparison 0 and -5 leads to (0 < -5). This is because 2’s complement representation of -5 is 251 and 0 < 251.

    Figure 1. Block Diagram of Magnitude Comparator

  2. Truth Table


    The truth table followed by the magnitude comparator is shown in Figure 2. A and B are the two 8-bit input signals to the comparator which compares the magnitude of these the two signals. The three 1-bit output signals are A < B, A = B and A > B.

    Figure 2. Truth Table of 8-bit Magnitude Comparator

  3. Verilog Module


    Figure 3 shows the Verilog module of the 8-bit magnitude comparator. The module has two 8-bit input port In1 and In2. There are three 1-bit output ports Eq, Gt, and Lt.

    Figure 3. Verilog module of 8-bit Magnitude Comparator

  4. Verilog Code for 8-bit Magnitude Comparator (magComp.v)


    1. module magComp ( In1,
    2. In2,
    3. Gt,
    4. Lt,
    5. Eq
    6. );
    7. input [7:0] In1,
    8. In2; //The two 8-bit Inputs In1 and In2
    9. output Gt,
    10. Lt,
    11. Eq; //The Outputs of comparison
    12. reg Gt,
    13. Lt,
    14. Eq;
    15. always @ (In1 or In2) //Check the state of the input lines
    16. begin
    17. Gt <= ( In1 > In2 )? 1'b1 : 1'b0;
    18. Lt <= ( In1 < In2 )? 1'b1 : 1'b0;
    19. Eq <= ( In1 == In2)? 1'b1 : 1'b0;
    20. end
    21. endmodule
    Figure 4. Verilog Code for 8-bit Magnitude Comparator

  5. Verilog Test-Bench of 8-bit Magnitude Comparator (magComp_tb.v)


    1. `timescale 1ns / 1ps
    2. module magComp_tb;
    3. // Inputs
    4. reg [7:0] In1;
    5. reg [7:0] In2;
    6. // Outputs
    7. wire Gt;
    8. wire Lt;
    9. wire Eq;
    10. // Instantiate the Unit Under Test (UUT)
    11. magComp uut (
    12. .In1(In1),
    13. .In2(In2),
    14. .Gt(Gt),
    15. .Lt(Lt),
    16. .Eq(Eq)
    17. );
    18. initial begin
    19. // Initialize Inputs
    20. In1 = 8'b0;
    21. In2 = 8'b0;
    22. // Wait 100 ns for global reset to finish
    23. #100;
    24. // Add stimulus here
    25. In1 = 8'd8;
    26. In2 = 8'd7;
    27. #20;
    28. In1 = 8'd100;
    29. In2 = 8'd120;
    30. #20;
    31. In1 = 8'd250;
    32. In2 = 8'd250;
    33. #20;
    34. In1 = 8'd0;
    35. In2 = -8'd5;
    36. #20;
    37. In1 = -8'd5;
    38. In2 = -8'd5;
    39. #20;
    40. end
    41. endmodule
    Figure 5. Verilog Test-bench for 8-bit Magnitude Comparator

  6. Timing Diagram


    Figure 6. Timing waveform of 8-bit Magnitude Comparator