问题描述:

Possible Duplicate:

How does Java handle integer underflows and overflows and how would you check for it?

How is System.out.println(4*2147483647) equal to -4 in java?

I want to know why this holds:

2 * Integer.MAX_VALUE == -2

I'm look forward to your response.

网友答案:

You get this result because of an integer overflow: in a two's complement system of representing negative integers, taking the max value which is 011.....112 and multiplying it by 2 gives you 11.....1102, which corresponds to -2.

网友答案:

That is because of the Integer overflow.

网友答案:

Integer.MAX_VALUE is 0x7FFFFFFF. Multiply by two and you get 0xFFFFFFFE (equivalent to shifting left one bit). This is a negative number (the first bit is 1) and is the binary representation of -2.

网友答案:

This is because of two's complement, where the lef most bit is used to signify if a number is positive (0) or negative (1). So when you add max int by itself (equivalent of multiplfy by two), this happens:

  011111111111111111111111
+ 011111111111111111111111
__________________________
  111111111111111111111110

and 111111111111111111111110 represents -2.

网友答案:

The MAX_VALUE of Int is 2^31 - 1 = 2147483647 = 0111 1111 1111 1111 1111 1111 1111 1111(binary number) the highest bit (here is the first bit 0, indicates the integer is a positive number, when 1 indicates negative.

(suppose the length of an integer is 4bytes), 2 * MAX_VALUE,in computer an integer by 2 times is left shift(operator << ) on bits, eg. 2 << 1 = 4; 2 << 2 = 8; so 0111 1111 1111 1111 1111 1111 1111 1111 << 1 become 1111 1111 1111 1111 1111 1111 1111 1110 which is equal to -2 in decimal.

相关阅读:
Top