简体   繁体   中英

why 32-bit signed integer maximum value change to minimum value after increment by 1 in c#?

If I have integer variable with maximum value assigned it which is (2,147,483,647) for 32 bit integer, and if I am incrementing it by 1 then it turn to (-2147483648) negative value

code

int i = int.MaxValue; // i = 2,147,483,647
i = i + 1;
Response.Write(i); // i = -2,147,483,648

Can anyone explain me? I did not find the exact reason for this change in values.

This is just integer overflow, where the value is effectively leaking into the sign bit. It's simpler to reason about it with sbyte , for example. Think about the bitwise representations of 127 and -127 as signed bytes:

 127: 01111111
-128: 10000000

Basically the addition is performed as if with an infinite range, and then the result is truncated to the appropriate number of bits, and that value "interpreted" according to its type.

Note that this is all if you're executing in an unchecked context. In a checked context, an OverflowException will be thrown instead.

From section 7.8.4 of the C# 5 specification:

In a checked context, if the sum is outside the range of the result type, a System.OverflowException is thrown. In an unchecked context, overflows are not reported and any significant high-order bits outside the range of the result type are discarded.

in signed int, first bit shows the sign and the rests shows the number: so, in 32bit int, first bit is the sign, so maxInt is: 2147483647 or 01111111111111111111111111111111 ,

and if we increment this number by 1 it will become: 10000000000000000000000000000000 which is - 2147483647

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM