Comparing signed with unsigned counterpart

This question is wrt comparing variables of same type but signed/unsigned.

In the following example branch B is printed because the variables are equal in their decimal format.

For printing “A” statement, do we need to type cast it to int?

module testbench;
  
  byte sign_i = 'b1000_0000;
  byte unsigned unsign_i = 'b1000_0000;
  
  initial
    begin
      if(sign_i < unsign_i)
        $display("A %0d %0d", sign_i, unsign_i);
      else
        $display("B %0d %0d", sign_i, unsign_i);
    end

endmodule : testbench

Also the signed numbers are represented by two’s complement?

If any operand of an arithmetic or relational expression are unsigned, all operands are considered unsigned. If you want sign_i to be treated as negative 128 and compared to positive 128, you need to widen the operands to more than 8 bits AND make both operands signed. So yes, casting to int will give you your desired result.

And yes, signed numbers are represented in 2’s complement.

2 Likes