-1 * int.MinValue == int.MinValue ?? This is mistake?

In C #, I see that

-1 * int.MinValue == int.MinValue 

This is mistake? It really screwed me up when I tried to inject a search tree. I ended up using (int.MinValue + 1) so that I can undo it correctly.

+46
c # integer-overflow
01 Sep '10 at 21:41
source share
5 answers

It's not a mistake.

int.MinValue * -1 has a value of 1 greater than int.MaxValue . So the number wraps back to int.MinValue .

This is mainly caused by integer overflow.

Int32.MinValue :

The value of this constant is -2,147,483,648

Int32.MaxValue :

The value of this constant is 2,147,483,647

So, -2,147,483,648 * -1 = 2,147,483,648 , which 1 greater than Int32.MaxValue .

+57
Sep 01 '10 at 21:43
source share

This is not a mistake, this is an overflow.

In two additional representations, the space of representable numbers is not symmetric. The opposite of the smallest number cannot be represented. Overflow calculation and redisplay of the same number.

+9
01 Sep '10 at 21:43
source share
 int i = -1 * int.MinValue; 

This does not even compile unless you disable the check:

 error CS0220: The operation overflows at compile time in checked mode 
+8
Sep 01 '10 at 21:44
source share

No, this is not a mistake. This is the nature of integer arithmetic.

For example, take a signed byte value that is between -128 and 127 .

127(0x7f)+1 = 128(0x80) . However, 0x80 is actually a binary representation of -128 .

So for byte 128(0x80) = -128(0x80)

So -128(0x80) * -1 = 128(0x80) = -128(0x80)

+2
Sep 01 '10 at 21:45
source share

Place the marked area on it and see that the โ€œerrorโ€ turns into an exception. Or try VB.NET (which, as far as I remember, is checked by default unlike C #).

+2
Nov 05 '10 at 23:51
source share



All Articles