Assume that you have two 8-bit 2's complement numbers, a[7:0] and b[7:0]. These numbers are added to produce s[7:0]. Also compute whether a (signed) overflow has occurred.
题意:可理解成数据溢出标志位的设置
Hint:A signed overflow occurs when adding two positive numbers produces a negative result, or adding two negative numbers produces a positive result. There are several methods to detect overflow: It could be computed by comparing the signs of the input and output numbers, or derived from the carry-out of bit n and n-1.
数据溢出一般在以下两种情况中发生:
1、两个正数相加产生负结果
2、两个负数相加产生正结果
解决思路:
1、当符号位相异时,两个数相加一定不会产生符号溢出,以4位2进制a,b为例(最高位为符号位)
如上式所示,a+b的结果在4位二进制可表示的范围内,即不会产生数据溢出,即
overflow = ~ (a[index_max] ^ b[index_max])
2、当符号位相同时,将a+b的结果的符号位与a或者b的符号位进行比较,若相同未溢出,即
sum = a + b
overflow = sum[index_max] == a[index_max] ? 0 : 1;
Code:
module top_module (
input [7:0] a,
input [7:0] b,
output [7:0] s,
output overflow
);
assign s = a + b;
assign overflow = ~(a[7]^b[7])&(s[7]==a[7] ? 0:1);
endmodule