In Verilog, I want to compare signed and unsigned values. The following code (val > valS) gave me unexpected result. In the code below, unsigned variable (val
) should be interpreted as "12", while signed variable (valS06
) should be interpreted as -4. So, I expect (val > valS) to be true, but the simulation result is (val < valS). Why the result is as such?
logic [3:0] val;
logic signed [5:0] valS06;
val=4'b1100;
valS06 = 6'b111100;
$display("val %04b | valS06 %b", val, valS06);
if(val>valS06 ) // <== should hit here
$display("val > valS");
else if(val==valS06)
$display("val == valS");
else
$display("val < valS"); // <= actually hit here --- why??
Log:
val 1100 | valS06 111100
val 12 | valS06 -4
val < valS
1 Answer 1
The problem is that you are comparing two things that are not alike.
From IEEE Std 1800-2023, section 11.4.4 Relational operators:
When one or both operands of a relational expression are unsigned, the expression shall be interpreted as a comparison between unsigned values.
You can cast the unsigned val
to signed using $signed
.
Also, the bit widths differ. You can explicitly pad the 4-bit value with zeroes to make their widths match:
if ($signed({2'b00, val}) > valS06)
$display("val > valS");
else if ($signed({2'b00, val}) == valS06)
$display("val == valS");
else
$display("val < valS");
This results in:
val > valS
Explore related questions
See similar questions with these tags.