Is this an overflow arithmetic calculation?

前端 未结 1 363
醉酒成梦
醉酒成梦 2021-01-24 12:54

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 conver

相关标签:
1条回答
  • 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
    0 讨论(0)
提交回复
热议问题