Search code examples
verilogsystem-verilog

Negative Floating Point Numbers


I have a situation where I need to pass negative floating-point number to an imported DPI-C function in SystemVerilog.

Below is pseudocode that I'm running but somehow it doesn't print a negative floating point number.

bit [5:0] a;
real      b;

b = (a[5] * -1) + (a[4] * 0.5) + (a[3] * 0.25) + (a[2] * 0.125) + (a[1] * 0.0625) + (a[0] * 0.03125)
`uvm_info(get_name(), $sformatf("value of b is: %.5f", b), UVM_MEDIUM)

For, 6'b111110

It prints, 4294967295.93750 instead of -0.03125

After calculating negative floating-point number, I need to pass it to a DPI-C function as real

Do you know what's wrong here?

I also tried taking 2's complement of b and then called $rtoi, divide integer by scaling factor of 5. But it results in 0.00000 as value of b is very small i.e -0.03125


Solution

  • -1 is interpreted as (I believe) a 32-bit integer. Use -1.0 for a real (floating-point) value:

    module tb;
    
    bit [5:0] a;
    real      b;
    
    initial begin
        a = 6'b111110;
        b = (a[5] * -1.0) + (a[4] * 0.5) + (a[3] * 0.25) + (a[2] * 0.125) + (a[1] * 0.0625) + (a[0] * 0.03125);
        #1;
        $display("value of b is: %.5f", b);
    end
    
    endmodule
    

    Prints:

    value of b is: -0.06250
    

    I get this output on 2 different simulators.