+ Post New Thread
Results 1 to 2 of 2
  1. #1
    Newbie level 1
    Points: 647, Level: 5

    Join Date
    Jun 2016
    Posts
    1
    Helped
    0 / 0
    Points
    647
    Level
    5

    Convert real to 2's complement & vice versa in Verilog

    Hello,

    I am trying to convert a real signed number into 2's complement in verilog for the sake of testing only. But I get "don't cares" when converting to binary. I am new to Verilog and not sure how to do it. My code is shown below:


    module tst();

    parameter INPUT_PORT_WIDTH = 65;

    // Input filter data {1,64} => Range -0.5 to 0.5 => 1 bit sign, 64 bits precision
    reg [INPUT_PORT_WIDTH-1:0] data_t;

    // Init a number between -0.5 to 0.5:
    real mynumber = -0.123;
    assign data_t = $realtobits(mynumber);

    // Converting back to real data:
    real converted_number = $bitstoreal(data_t);

    initial
    begin
    $display("======================================> The original number: %f", mynumber);
    $display("======================================> The bits number : %b", data_t);
    $display("======================================> The restored number: %f", converted_number);
    end

    endmodule

    Output:

    ncsim> run
    ======================================> The original number: -0.123000
    ======================================> The bits number : xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxx
    ======================================> The restored number: 0.000000
    ncsim: *W,RNQUIE: Simulation is complete.
    ncsim> exit


    I tried to change the number to a regular integer "ex: 123", but I got (don't care output) as well. Please help!

    •   AltAdvertisement

        
       

  2. #2
    Super Moderator
    Points: 263,431, Level: 100
    Awards:
    1st Helpful Member

    Join Date
    Jan 2008
    Location
    Bochum, Germany
    Posts
    46,034
    Helped
    13998 / 13998
    Points
    263,431
    Level
    100

    Re: Convert real to 2's complement & vice versa in Verilog

    You should read the description of conversion functions in clause 20.5 of the Verilog LRM.

    $realtobits() is generating 64 bit IEEE float value.

    You can use $rtoi() or automatic type conversion. Both are truncating to integer, you need to scale the real value to the intended fixed point representation, e.g. integer value = $rtoi(1000.0 *0.123) in your example.



--[[ ]]--