So when I read the book and it says that overflow can't occur when add different signs and subtraction of the same sign. But I have question when I do this: 185 - 122 I converted binary of 122 to 2s complement and did the addition, which is different signs: 185+(-122) and when I add them together, I got the sign bit overflow to 100111111. But if I cut off the MSB on the left, it is the correct answer. Is it an overflow?
No, it isn't overflow - the overflow resulting from the addition of 2 1's
in the MSB must just be discarded. From Wikipedia
To get the two's complement of a binary number, the bits are inverted, or "flipped", by using the bitwise NOT operation; the value of 1 is then added to the resulting value, ignoring the overflow which occurs when taking the two's complement of 0.
So in your example
185 10111001
122 01111010 -
Taking the 2's complement of 122 (One's complement +1)
01111010 => 10000110
Adding:
10111001 185
10000110 +(-122)
--------
00111111 (63)
=63
The overflow
is ignored.
There are however rules for detecting overflow after doing the 2's complement :
- If the sum of two positive numbers results in a negative result
- If the sum of two negative numbers results a positive result
来源:https://stackoverflow.com/questions/21965130/is-this-an-overflow-arithmetic-calculation