Verilog系统函数实现单精度float、双精度doble浮点类型和整型之间互相转换

标准verilog支持双精度double类型和十六进制64位数据相互转换,使用$realtobits$bitstoreal系统函数
使用示例:

//test_tb.v
`timescale 1ns/1ps

module test_tb;

real data_real;
reg [63:0] data_hex;

initial begin

    data_real = 0;
    data_hex = 0;

    data_real = 1234.567891;
    data_hex = $realtobits(data_real);      //40934A458537E2C5
    $display("data_real = %.6f, data_hex=0x%x", data_real, data_hex);

    data_hex = 64'hC1678C29C3F35BA7;       //double = -12345678.123456789
    data_real = $bitstoreal(data_hex);
    $display("data_real = %.6f, data_hex=0x%x", data_real, data_hex);
    
    $stop(0);
end
/*
# data_real = 1234.567891, data_hex=0x40934a458537e2c5
# data_real = -12345678.123457, data_hex=0xc1678c29c3f35ba7
*/

endmodule   //test_tb end

如果需要单精度float类型和32位十六进制互相转换,可以使用SystemVerilog中的$shortrealtobits$bitstoshortreal系统函数,SystemVerilog完全兼容verilog,而且增加了很多新的特性。

//test.sv
`timescale 1ns/1ps

module test_tb;

shortreal data_real;
reg [31:0] data_hex;

initial begin

    data_real = 0;
    data_hex = 0;

    data_real = 1234.567891;
    data_hex = $shortrealtobits(data_real);      //449A522C
    $display("data_real = %.6f, data_hex=0x%x", data_real, data_hex);

    data_hex = 32'h45B170FD;       //double = -5678.12345
    data_real = $bitstoshortreal(data_hex);
    $display("data_real = %.6f, data_hex=0x%x", data_real, data_hex);
    
    $stop(0);
end
/*
# data_real = 1234.567891, data_hex=0x449a522c
# data_real = 5678.123535, data_hex=0x45b170fd
*/

endmodule   //test_tb end

注意:系统函数只可以在仿真时使用,不可综合。

你可能感兴趣的:(Xilinx,FPGA,ZYNQ,verilog,systemverilog)