|
算法常见基本的问题:signed data除了在硬件架构上需要注意signed-bit的加法运算外,overflow 也是一个很重要需要处理的问题,若处理不好,debug也是很费时费力。承接上面的分享,这边把输出从“5-bit output”改成“4-bit output”。
使用Verilog实现 “signed_add.v”(for 4-bit input and 4-bit output)
module signed_add (
iclk,
ia,
ib,
osum
);
input iclk;
input [3:0] ia;
input [3:0] ib;
output [3:0] osum;
reg [3:0] osum;
wire [4:0] sum_temp;
assign sum_temp = {ia[3], ia} + {ib[3], ib};
always@(posedge iclk)
if (!sum_temp[4] && sum_temp[3]) //Note here!
osum <= 4’h7;
else if (sum_temp[4] && !sum_temp[3]) //Note here!
osum <= 4’h8;
else
osum <= sum_temp;
endmodule
sum_temp[4]:signed bit
sum_temp[3]:overflow bit
判断是否为正overflow:sum_temp[4]为0且sum_temp[3]为1
判断是否为负overflow:sum_temp[4]为1且sum_temp[3]为0 |
|