Home > Enterprise >  Why Negating An Integer In Two's Complement and Signed Magnitude Can Result In An Overflow?
Why Negating An Integer In Two's Complement and Signed Magnitude Can Result In An Overflow?

Time:09-30

I dont quite understand, if someone can provide examples to help me understand better. It would be greatly appreciated.

CodePudding user response:

On a system using 2's complement and a 32-bit int, the range of values it can hold is -2147483648 to 2147483647.

If you were to negate the smallest possible int, i.e. -2147483648, the result would be 2147483648 which is out of range.

A sign-and-magnitude system cannot overflow in this way because 1 bit is reserved solely as a sign bit while the remaining bits (assuming no padding) are the value.

CodePudding user response:

You can't get an overflow in sign-magnitude format. Negating the number simply inverts the sign and keeps the magnitude the same.

In two's complement, you get an overflow if you try to negate the most negative value, because there's always 1 more negative value than positive values. For instance, in 8 bits the range of values is -128 to 127. Since there's no 128, you get an overflow if you try to negate -128.

CodePudding user response:

As 2's complement numbers do not have negative zero - they have only one zero so the number of the negative numbers is larger than the number of the positive numbers.

If you negate the minimum negative number you will get number which cannot be represented as a positive number of the same length.

  •  Tags:  
  • c
  • Related