2

I am confused as to when the '-' sign is used and when 's' is used. This post is somewhat helping, although not entirely.

Please correct if I am wrong:

For example, to interpret 8'sd244, we write 244 in binary = 11110100. Now it is signed, so the MSB tells us that it is a negative number. So the remaining bits are in 2's complement form, so the actual number stored is -12.

Now when we declare -16'h3A, this is actually 16'hFFC6 in 2's complement form. So declaring these should be equivalent. But how does Verilog know that 16'hFFC6 must be interpreted as a 2's complement number?

In other words, are the below the same?

a = 16'hFFC6;

and

a = -16'h3A;

Is it different in SystemVerilog and Verilog?

ocrdu
  • 8,705
  • 21
  • 30
  • 42
SM32
  • 366
  • 2
  • 12
  • 1
    It is "interpreted" only in some certain context. If that context is an arithmetic expression involving signed types, then it is interpreted as signed. – Eugene Sh. Sep 19 '22 at 16:41
  • @EugeneSh. then a = 16'hFFC6 can be unsigned or signed representation, but unless we specify it to be signed (how to do that?) it is taken as unsigned by default? – SM32 Sep 19 '22 at 18:17
  • It depends on the type of `a`. In Verilog-2001 you can specify the signedness even for registers and wires. – Eugene Sh. Sep 19 '22 at 18:25
  • Small example: https://www.edaplayground.com/x/gUXD - here you can see that the same hex value is interpreted as signed or unsigned when it is passed to `$display` function - based on it's type only. – Eugene Sh. Sep 19 '22 at 18:39

1 Answers1

3

The - symbol is an operator, not a value. Values get stored in binary and it's only when the value is used as an operand in a larger expression that it matters whether the value gets treated as signed or unsigned.

The numeric literals 8'sd244 and 8'd244 both represent the same bit pattern 8'b11110100 (or `8'hF4), and that's the pattern that gets stored in an 8-bit variable regardless of whether that variable is signed or unsigned. But if you want to compare that pattern with another signed value, or store the pattern in a larger variable, the the signedness becomes important.

(8'sd244 < 10) is true because this gets evaluated as 32'hFFFF_FFF4 < 32'h0000_000A

(8'd244 < 10) is false because this gets evaluated as 32'h0000_00F4 < 32'h0000_000A

SystemVerilog did not change anything in this area with respect to how it deals with Verilog signed arithmetic.

dave_59
  • 7,557
  • 1
  • 14
  • 26
  • So if I wanted to convert -75 into an 8bit hex number in verilog, would it be -8'h4B or would it be 8'shCB? (75 in binary 1001011, another 1 for signed : 11001011) or would it be 8'h35 in the 2's complement form? (1001011 is 75 -> 2's complement is hex 35) – SM32 Sep 19 '22 at 19:53