开发者

Can someone explain to me why overflow always occurs when the last and second last carry bit are different?

开发者 https://www.devze.com 2023-02-05 05:07 出处:网络
overflow = c,n ⊕ c,n−1 I tried it with all four possible cases c,nc,n-1 -7+21001+001000 7+20111+001001
overflow = c,n ⊕ c,n−1

I tried it with all four possible cases

                            c,n   c,n-1
-7+2      1001+0010         0     0         
7+2       0111+0010         0     1
-7+(-2)   1001+1110         1     0
7+(-2)    01开发者_如何学编程11+1110         1     1 

and it seems to work, but can someone explain or prove why?


When adding two numbers with n bits, the result can have n+1 bits. This means that by using n bits for result we cannot represent all of them.

Now, what is an overflow? If we consider a signed number, it will mean that we can extend the number by adding sign bit (MSB) above MSB, and they will be equal. So, when this does not hold (next bit after MSB is not equal to MSB, something that can be detected before truncating the result to n bits), then we say it's overflow.

As is your example, we say that the overflow occurs when after adding two positive number we obtained a negative one (or two negative that gave positive result).

Also, check this answer by Thomas Pornin, I think he explained it wery well.


It's been so long, I have only a vague understanding of what the notation is saying. I'd assume that 'c' is a carry flag, and 'n' is a negative flag. But then what is 'n-1'?

Anyway, I'm guessing your answer pertains to overflow occurring in either direction: from a negative number wrapping over into a positive, and a positive wrapping over into a negative.

0

精彩评论

暂无评论...
验证码 换一张
取 消