0

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

Jay
  • 1
  • Does this answer your question? [Why is unsigned integer overflow defined behavior but signed integer overflow isn't?](https://stackoverflow.com/questions/18195715/why-is-unsigned-integer-overflow-defined-behavior-but-signed-integer-overflow-is) – diggusbickus Oct 01 '21 at 00:00

3 Answers3

1

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Similarly, integer division can overflow, if you try to compute `INT_MIN / -1`. – Steve Summit Sep 29 '21 at 23:00
  • Isn't that essentially the same, since dividing by a negative is equivalent to negating and dividing by the absolute value, or dividing by the absolute value and negating the result? – Barmar Sep 29 '21 at 23:02
  • Sure — I'm basically just kibitzing here. It is a surprising result, though. (There've been [questions](https://stackoverflow.com/questions/30394086) about it — [more than once](https://stackoverflow.com/questions/58881636).) – Steve Summit Sep 29 '21 at 23:17
0

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.

0___________
  • 60,014
  • 4
  • 34
  • 74