Verilog Coding Tips and Tricks: Verilog Code for 4 bit Comparator

Monday, October 19, 2015

Verilog Code for 4 bit Comparator

There can be many different types of comparators. Here, I have designed, a simple comparator with two 4 bit inputs and three output bits which says, whether one of the input is less,greater or equal to the second input.

The code is written in behavioral model. Even though it checks for 4 bit inputs, the code can be extended for other input sizes with very small changes.

4 bit Comparator:

//declare the Verilog module - The inputs and output signals.
module comparator(
    Data_in_A,  //input A
    Data_in_B,  //input B
    less,       //high when A is less than B
    equal,       //high when A is equal to B
     greater         //high when A is greater than B    

    //what are the input ports.
    input [3:0] Data_in_A;
    input [3:0] Data_in_B;
    //What are the output ports.
    output less;
     output equal;
     output greater;
     //Internal variables
     reg less;
     reg equal;
     reg greater;

    //When the inputs and A or B are changed execute this block
    always @(Data_in_A or Data_in_B)
        if(Data_in_A > Data_in_B)   begin  //check if A is bigger than B.
            less = 0;
            equal = 0;
            greater = 1;    end
        else if(Data_in_A == Data_in_B) begin //Check if A is equal to B
            less = 0;
            equal = 1;
            greater = 0;    end
        else    begin //Otherwise - check for A less than B.
            less = 1;
            equal = 0;
            greater =0;

Testbench for Comparator:

module tb_tm;

    // Inputs
    reg [3:0] Data_in_A;
    reg [3:0] Data_in_B;

    // Outputs
    wire less;
    wire equal;
    wire greater;

    // Instantiate the Unit Under Test (UUT)
    comparator uut (

    initial begin
        //Apply inputs
        Data_in_A = 10;
        Data_in_B = 12;
        Data_in_A = 15;
        Data_in_B = 11;
        Data_in_A = 10;
        Data_in_B = 10;

Simulation waveform:

The codes when correctly simulated, will show you the following waveform in Xilinx ISE 13.1.

1 comment: