Verilog实现SQ4.4定点数计算器时减负数运算结果错误如何解决
核心问题原因
你代码中所有位宽声明未加signed修饰符,Verilog默认将这类变量判定为无符号数,所有运算按无符号规则执行,这是出错的根本原因:
- 测试代码中
n2 = -2赋值时,-2的8位补码为8'hFE,由于n2是无符号8位变量,实际存储的值是无符号数254,而非有符号数-2 - 执行
0 - n2运算时,无符号数会做高位补0的扩展:8'h00扩展为16'h0000,8'hFE扩展为16'h00FE,无符号运算0 - 254的16位无符号结果就是16'hFF02,和你得到的错误结果完全匹配 - 直接写
res = - (-2)时运算正常,是因为字面量默认按有符号整数处理,运算规则符合预期
修复方案
有两种可行的修改方式:
方案1:运算时用$signed系统任务转换操作数
无需修改变量定义,仅修改calc模块的运算逻辑,将无符号数强制转换为有符号数参与运算:
`define SUM 2'b00 `define SUB 2'b01 `define MUL 2'b10 module calc( output reg [15:0] res, input [7:0] n1, n2, input [1:0] op); always @ (n1, n2, op) case (op) `SUM: res = $signed(n1) + $signed(n2); `SUB: res = $signed(n1) - $signed(n2); `MUL: res = ($signed(n1)*$signed(n2)) >>> 8; // 有符号移位必须用算术右移>>> default: res = 16'hffff; endcase endmodule
方案2:直接将变量声明为有符号类型
修改所有参与有符号运算的变量定义,加上signed修饰符:
- calc模块修改:
`define SUM 2'b00 `define SUB 2'b01 `define MUL 2'b10 module calc( output reg signed [15:0] res, input signed [7:0] n1, n2, input [1:0] op); always @ (n1, n2, op) case (op) `SUM: res = n1 + n2; `SUB: res = n1 - n2; `MUL: res = (n1 * n2) >>> 8; default: res = 16'hffff; endcase endmodule
- 测试平台模块对应修改变量定义:
module tb(); wire signed [15:0] res; reg signed [7:0] n1, n2; reg [1:0] op; // 剩余逻辑无需修改 endmodule
额外注意事项
你当前乘法逻辑的移位位数需要确认:SQ4.4格式的两个数相乘,结果为SQ8.8格式,若要输出SQ4.4格式的结果,正确的算术右移位数是4位而非8位,当前右移8位会直接丢弃全部小数位,仅保留整数部分,和你设定的定点数格式不匹配。
内容的提问来源于stack exchange,提问作者Martel
相关产品推荐
相关产品推荐

