verilogvivado

How to print the correct value of a signed reg variable?


`timescale 1ns/1ps
module a(
input a,
output [7:0]tmp
);
reg signed[2:0] m;
reg [2:0] n;

initial begin
m=4;
n=4;
$display("%f",m);//-4.000000
$display("%f",n);//4.000000
end
endmodule

As m=4,$display outputs the wrong value: -4.
How do I output the correct value 4 for signed variable m=4?


Solution

  • For signed, two’s complement values, the range of an N bit number is given by
    -2^(N-1) <= m <= 2^(N-1) -1

    A three bit number can represent values between -4 and +3 inclusive.

    Explanation and more on FPGA bit widths here: zip cpu bit-growth

    Verilog

    `timescale 1ns/1ps
    module a();
      // NEED ANOTHER BIT reg signed[2:0] m;
      reg signed[3:0] m;
      initial begin
      m=4;
      // treat var as float
      $display("%f",m);
      // treat var as original radix
      $display("%d",m);
      end
    endmodule
    

    Produces

    xcelium> run
    4.000000
    4
    xmsim: *W,RNQUIE: 
    Simulation is complete.xcelium> exit