You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Verilog IEEE 754单精度浮点数转换模块及测试平台错误修复

浮点数转IEEE 754单精度格式Verilog实现及验证

问题修复说明

原代码存在以下问题:

  • 数组声明语法错误
  • wire类型变量进行过程赋值(Verilog中wire仅支持连续赋值)
  • 数组索引使用错误
  • 未正确实现浮点数到IEEE 754格式的转换逻辑

以下是修复后的完整实现代码:

转换模块代码

module float_to_ieee754_single_precision (
  input real float_input, // 输入十进制浮点数
  output reg [31:0] ieee754_single_precision // 输出IEEE 754单精度格式的32位二进制
);

reg sign;
reg [7:0] exponent;
reg [22:0] mantissa;
real abs_float;

always @(*) begin
  // 处理符号位:负数为1,正数为0
  sign = (float_input < 0) ? 1'b1 : 1'b0;
  abs_float = (float_input < 0) ? -float_input : float_input;

  // 处理输入为0的特殊情况
  if (abs_float == 0.0) begin
    exponent = 8'h00;
    mantissa = 23'h000000;
  end else begin
    // 归一化处理:将浮点数调整到[1,2)区间
    integer exp_count;
    exp_count = 0;
    while (abs_float >= 2.0) begin
      abs_float = abs_float / 2.0;
      exp_count = exp_count + 1;
    end
    while (abs_float < 1.0) begin
      abs_float = abs_float * 2.0;
      exp_count = exp_count - 1;
    end

    // 计算偏移指数:IEEE 754单精度偏移量为127
    exponent = exp_count + 127;

    // 获取尾数:去掉隐含的最高位1,保留23位小数部分
    mantissa = (abs_float - 1.0) * 2**23;
  end

  // 拼接成完整的IEEE 754单精度格式:符号位(1) + 指数位(8) + 尾数位(23)
  ieee754_single_precision = {sign, exponent, mantissa};
end

endmodule

测试平台代码

`timescale 1ns / 1ps

module float_to_ieee754_single_precision_tb;
  reg real float_input;
  wire [31:0] ieee754_single_precision;

  // 例化被测转换模块
  float_to_ieee754_single_precision dut (
    .float_input(float_input),
    .ieee754_single_precision(ieee754_single_precision)
  );

  // 测试向量:{输入浮点数, 预期IEEE 754输出值}
  localparam struct {
    real input_val;
    logic [31:0] expected;
  } test_vector[4:0] = '{
    '{1.0, 32'h3F800000},
    '{1.1, 32'h3F8CCCCD},
    '{-1.1, 32'hBF8CCCCD},
    '{10.0, 32'h40A00000},
    '{3.817, 32'h40791EB8} // 3.817对应的IEEE 754单精度标准值
  };

  integer i;
  initial begin
    for (i = 0; i < 5; i = i + 1) begin
      float_input = test_vector[i].input_val;
      #10;
      $display("测试用例 %d: 输入=%.3f", i, test_vector[i].input_val);
      $display("  预期输出: %h", test_vector[i].expected);
      $display("  实际输出: %h", ieee754_single_precision);
      if (ieee754_single_precision != test_vector[i].expected) begin
        $display("  测试失败!");
      end else begin
        $display("  测试通过!");
      end
      #10;
    end
    $finish;
  end
endmodule

内容的提问来源于stack exchange,提问作者S_ZeroX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 18:55:27