HDLBits刷题—Exams/ece241 2014 q1c(最简方法)

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、两个正数相加产生负结果     (e.g.\ 0101_{(2)}+0100_{(2)}=1001_{(2)}=-1_{(10)})

2、两个负数相加产生正结果     (e.g. \ 1100_{(2)}+1010_{(2)}=0110_{(2)}=6_{(10)})

解决思路:

1、当符号位相异时,两个数相加一定不会产生符号溢出,以4位2进制a,b为例(最高位为符号位)

\left\{\begin{matrix}-7_{(10)}=1111_{(2)}\leqslant a\leqslant 0 \\ 0\leqslant b\leqslant 0111_{(2)}=7_{(10)} \end{matrix}\right.

7_{(10)}=1111_{(2)}\leqslant a+b\leqslant 0111_{(2)}=7_{(10)}

如上式所示,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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值