Verilog design for two complement comparators

I am trying to write some simple verilog code for a comparator of two four-bit two add-on numbers. I have two 4-bit inputs (A [3: 0], B [3: 0]) and 3 outputs (AeqB, AgtB, AltB) to show if A and B are equal if A is greater than B, or less B. There is also a third input character with a name, which, if 0 means unsigned numbers, and if 1, numbers are signed.

So, I know that the two signed two add-on numbers can be compared by subtracting them, but I cannot get this to work properly in my design. Here is what I tried:

if(sign==0)
 begin

    if(({sign,A}-{sign,B})==0)
        AeqB = 1;
    else if(({sign,A}-{sign,B}) > 0)
        AgtB = 1;
    else if (({sign,A}-{sign,B}) < 0
        AltB = 1;
end

It seems like this should work. I concatenate the sign bit in front of the four bit numbers, subtract them, and then check to see if they are greater than or equal to zero. If AB <0, then B is less than A, since they are both negative numbers.

However, when I simulate this construct, it is correct whenever A = B, but shows AgtB in every other case, never AltB.

Any ideas on what I'm doing wrong?

0
source share
1 answer

I'm not sure what you are doing with {sign,A}. This will cause the numbers to be negative if they have a signed format. If the sign does not cause them to be negative?

, , , 0 msb , , , - . , , , .

if (sign) begin
   A_i = {A[3], A};
   B_i = {B[3], B};
end
else begin
   A_i = {1'b0, A};
   B_i = {1'b0, B};
end

AgtB = $signed(A_i) > $signed(B_i) ;
AltB = ~AgtB ;

- +1. 0 unsigned. , MSB.

2- , 4- .

:

   3 : (0)0011 
 + 1 : (0)0001
 = 4 :  0 0100    

:

  15 :  (0)1111 //Zero pad for correct bitwidths
 + 1 :  (0)0001
 =16 :   1 0000

():
(01) MSB 4

   7 : (0)0111
  +1 : (0)0001
  =8 :  0 1000 bits

:

   7 : (0)0111
  -1 : (1)1111 //(twos complement of 1)
  // Sum the bits as you did for unsigned
  =6 :  0 0110  
+1

Source: https://habr.com/ru/post/1544158/


All Articles