Do we ignore overflow in Two's Complement

前端 未结 2 913
时光取名叫无心
时光取名叫无心 2021-01-24 10:31

I\'m trying to wrap my head around overflow within twos complement for example say I\'m trying to take away these two binary numbers: 1111 1000 0100 - 010 111 001 000

I

2条回答
  •  清歌不尽
    2021-01-24 11:15

    Short answer:

    if you are performing arithmetic on fixed-width binary numbers, using two's complement representation for negative numbers, then yes, you ignore the one-bit overflow.

    Long Answer:

    You can consider each ith bit in n-bit two's complement notation have place value 2^i, for 0 <= i < n - 1, with bit n - 1 (the sign bit) having place value -2^(n - 1). That's a negative place value for the sign bit. If you compute the sum of two such numbers as if they were unsigned n-bit binary numbers, these cases are fine:

    • the sign bit is not set in the either addend or in the result (reinterpreted as being in two's-complement representation),
    • the sign bit is set in exactly one of the addends, regardless of overflow (which is ignored if it occurs), or
    • the sign bit is set in both addends (therefore there is an overflow, which is ignored) and in the result.

    To understand that, it may be easier to think about the problem as two separate sums: a sum of the sign bits, and a sum of the value (other) bits. An overflow of the value sum yields an overflow bit whose place value is 2^(n-1) -- exactly the inverse of the place value of a sign bit -- therefore such an overflow cancels one sign bit.

    The negative + negative case requires such a cancellation for the result to be representable (two sign bits + one value overflow = one sign bit), and the positive + positive case cannot accommodate such a cancellation because there is no sign bit available to be cancelled. In the positive + negative case, there is an overflow of the value-bit sum in exactly those cases where the result is non-negative; you can consider that to cancel the sign bit of the negative addend, wich yields the same result as ignoring the overflow of the overall unsigned sum, and reinterpreting the sum as a two's complement number.

    The remaining cases yield mathematical results that cannot be represented in n-bit two's complement format -- either greater than the largest representable number, or less than the smallest. If you ignore overflow then such results can be recognized by an apparent sign flip. What you do with that is a question of error recovery strategy.

提交回复
热议问题