1
\$\begingroup\$

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
toolic
10.8k11 gold badges31 silver badges35 bronze badges
asked Aug 30, 2024 at 12:56
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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
answered Aug 30, 2024 at 13:43
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.