Search code examples
compareveriloghdl

Verliog- comparator


  1. For two 3-bit unsigned numbers a (a2a1a0)and b (b2b1b0), build a logic circuit to output the larger number.
  2. I want to compare three bits number and show the larger number. But the code can not work.
  3. I cannot find the mistake i have made.

    4.ABTB=A is bigger than B

module comparator(
    input [2:0]A,
    input [2:0]B,
    output reg [2:0]out,
    output ABTB,
    output ASTB,
    output AEQB
    );
assign ABTB=(A[2]&(~B[2]))||((~((A[2]&(~B[2]))||((~A[2])&B[2])))&(A[1]&(~B[1])))||((~((A[2]&(~B[2]))||((~A[2])&B[2])))&(~((A[1]&(~B[1]))||((~A[1])&B[1])))&(A[0]&(~B[0])));
assign ASTB=((~A[2])&B[2])||((~((A[2]&(~B[2]))||((~A[2]&B[2])))&((~A[1])&B[1])))||((~((A[2]&(~B[2]))||((~A[2])&B[2])))&(~((A[1]&(~B[1]))||((~A[1])&B[1])))&((~A[0])&B[0]));
assign AEQB=(~((A[2]&(~B[2]))||((~A[2])&B[2])))&(~((A[1]&(~B[1]))||((~A[1])&B[1])))&(~((A[0]&(~B[0]))||((~A[0])&B[0])));

always@*
if(ABTB==1)
assign out=A;
else if(ASTB==1)
assign out=B;
else if(AEQB==1)
assign out=A;


endmodule

module test_comparator;
    reg [2:0]A;
    reg [2:0]B;

    wire ABTB;
    wire ASTB;
    wire AEQB;
comparator u0(.a(a),.b(b),.abtb(abtb),.astb(astb),.aeqb(aeqb));

initial
begin

A=000;B=001;
#10 A=001;B=001;
#10 A=010;B=001;
#10 A=011;B=001;
#10 A=100;B=001;
#10 A=101;B=001;
#10 A=110;B=001;
#10 A=111;B=001;
#10 A=001;B=001;
#10 A=001;B=001;
#10 A=001;B=001;

end
endmodule

Solution

  • The condition (A>B) can be expressed as (for 3-bit inputs A and B):

    assign Bit_3 = A[2] & (~B[2]);
    assign Bit_2 = (A[2] ^~ B[2]) & (A[1] & (~B[1]));
    assign Bit_1 = (A[2] ^~ B[2]) & (A[1] ^~ B[1]) & (A[0] & (~B[0]));
    
    assign ABTB = (Bit_3 | Bit_2 | Bit_1);
    

    Then you can set out as:

    assign out = (ABTB) ? A : B;