2
\$\begingroup\$

I'm trying to use the display function in Verilog to print the 2's complement of a binary number.

E.g. I have the following testbench output being printed:

Test 1 data: input A is 0b'0011010100100100 or 0h'3524 or 13604 ;

Test 2 data: input A is 0b'1101011000001001 or 0h'd609 or 54793 ;

Test 3 data: input A is 0b'0111101100001101 or 0h'7b0d or 31501 ;

And I use the following code to generate that:

$display ("Test %0d data: input A is 0b'%16b or 0h'%4h or %d ;", counter,X,X,X);

But I would like the decimal %d of the variable to be printed in 2's complement.

So for the middle example 0xd609, the decimal should be -10743 not 54793.

How to do it?

\$\endgroup\$
0

2 Answers 2

2
\$\begingroup\$

It would have really helped to show a complete example. X needs to be declared as signed, or you can cast it to a signed type value.

module top;
  bit signed [15:0] X;
  bit        [15:0] Y;
  initial begin 
    X = 'hd609;
    Y = 'hd609;
    $display ("Test %0d data: input A is 0b'%16b or 0h'%4h or %d ;", 1,X,X,X);
    $display ("Test %0d data: input A is 0b'%16b or 0h'%4h or %d ;", 2,Y,Y,Y);
    $display ("Test %0d data: input A is 0b'%16b or 0h'%4h or %d ;", 3,Y,Y,$signed(Y));
  end
endmodule

Displays

Test 1 data: input A is 0b'0011010100100100 or 0h'3524 or 54793 ;

Test 2 data: input A is 0b'1101011000001001 or 0h'd609 or -10743 ;

Test 3 data: input A is 0b'0111101100001101 or 0h'7b0d or -10743 ;
\$\endgroup\$
1
  • \$\begingroup\$ FWIW, I get quite different results simulating the above (after changing bit to reg for Verilog vs. System Verilog) : Simulator is doing circuit initialization process. Test 1 data: input A is 0b' 1101011000001001 or 0h'd609 or -10743 ; Test 2 data: input A is 0b' 1101011000001001 or 0h'd609 or 54793 ; Test 3 data: input A is 0b' 1101011000001001 or 0h'd609 or -10743 ; \$\endgroup\$ Commented Mar 5, 2023 at 6:38
0
\$\begingroup\$

$display will behave as you wish if the variable is declared as signed.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.