简体   繁体   English

二进制加法中的下溢和上溢

[英]Underflow and Overflow in binary addition

In the case of: 如果是:

0b10001111+0b10011000 = 0b100100111 

Is a case of underflow? 是否有下溢的情况? as the two term are negative and the result it positive? 因为两个项都是负数,结果是正数?

When will we get an overflow? 我们什么时候会溢出? as the 9th bit will be always 1? 因为第9位将始终为1? when both of the 8th bits are 1 当第8位都为1时

0b1000 1111+0b1001 1000 = 0b1 0010 0111 0b1000 1111 + 0b1001 1000 = 0b1 0010 0111

Including the carry as n+1th bit of result in meaningless for 2s complement. 包含进位作为结果的第n + 1位对2s补码毫无意义 What you can do is either to stick on the original size 您可以做的就是坚持原始大小

0b1000 1111+0b1001 1000 = 0b0010 0111 // invalid 0b1000 1111 + 0b1001 1000 = 0b0010 0111 //无效

or extend operands to n+1 bits and get a n+1 bits result. 或将操作数扩展到n + 1位,并得到n + 1位结果。

0b1 1000 1111+0b1 1001 1000 = 0b1 0010 0111 //valid 0b1 1000 1111 + 0b1 1001 1000 = 0b1 0010 0111 //有效

The reason is that 2s complement works by adding 2^n to negative integers to make them positive. 原因是2s补码通过向负整数加上2 ^ n以使其为正来起作用。 (to code a<0=-|a|, use 2^n+a or 2^n -|a|, ie the complement to 2^n of |a|, hence the name of 2s complement). (要编码a <0 =-| a |,请使用2 ^ n + a或2 ^ n- | a |,即| a |对2 ^ n的补码,因此命名为2s补码)。

This is great, as the coded value is (2^n)+a if a<0 or a if a≥0, and if you ignore 2^n, you can do signed integer addition without worrying on the sign of operands. 很好,因为如果a <0或a≥0,则编码值为(2 ^ n)+ a,并且如果忽略2 ^ n,则可以进行带符号整数加法,而不必担心操作数的符号。 But you must ignore the carry out (except for what concerns validity). 但是您必须忽略执行(除了有效性方面的问题之外)。

To get the precise validity rules, you must consider the different situations: 要获得精确的有效性规则,必须考虑不同的情况:

1/A,B>=0 1 / A,B> = 0

在此处输入图片说明

Result is valid iff MSB=0 ⇒ c_n-1=0 (and we always have c_n=0) 当MSB = 0⇒c_n-1 = 0时,结果是有效的(而且我们总是c_n = 0)

2/ A,B<0 2 / A,B <0

在此处输入图片说明

Result is valid iff MSB=1 ⇒ c_n-1=1 (and we always have c_n=1) 当MSB = 1⇒c_n-1 = 1时结果是有效的(并且我们总是c_n = 1)

3/ A>=0, B<0 3 / A> = 0,B <0

在此处输入图片说明

Result cannot be too positive or too negative and is always valid. 结果不能为正或为负,且始终有效。 And we always have c_n=c_n-1 而且我们总是c_n = c_n-1

We can see that the global rule that indicates if a result is valid is that c_n==c_n-1 (or c_n ⊕ c_n-1 indicates overflow). 我们可以看到,指示结果是否有效的全局规则是c_n == c_n-1(或c_n = c_n-1指示溢出)。

There are many other equivalent rules. 还有许多其他等效规则。 For instance: 例如:
result is valid if (sign(A) != sign(B)) or ((sign (A) == sign(B)) and (sign(A)==sign(A+B)) 如果(sign(A)!= sign(B))或((sign(A)== sign(B))和(sign(A)== sign(A + B))
which can be expressed in C as 可以用C表示为
((a^b) | (a^~(a+b)))&(1<< sizeof (int) -1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM