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

I am starting Java and am rather confused about this.

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

+5
source share
6 answers

This is due to a whole quiet overflow.

2147483647 == Integer.MAX_VALUE is the maximum value for an integer.

Silent overflow means 2147483647 + 1 == Integer.MIN_VALUE = -2147483648
Then you can see that2147483647 + 2147483647 == 2147483647 + (-2147483648 + - 1) == -2

In other words,, 2147483647 * 2 == -2and now you can see why 2147483647 * 4 == -4.

More technically, the result is determined by the Java Language Specification # 15.17.1 :

, , . , , , .

+27

, . , , - , 0111111111111111111111111 ( , , ).

mutiply 4, 2, 11111111111111111111100 ( -4). , .

+13

int.

, long int.

+3

, int (4 ) (8 )

System.out.println(4*2147483647);

l ( ) , , . Integer http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html#MAX_VALUE

System.out.println(4l * 2147483647);

System.out.println(4 * 2147483647l);

. 8589934588

+1

32-, 4 ( 64 ). 4 294 967 295 32- . , 4 294 967 295 + 5 . 5. -1 4 294 967 295 . .

: http://en.wikipedia.org/wiki/Integer_overflow

http://en.wikipedia.org/wiki/Integer_(computer_science)

0

- , . 2147483647 * 4 = 8589934588

8589934588 1 1111 1111 1111 1111 1111 1111 1111 1100

- , , , , .

The next part can be explained by two additions.

Two additions is a way of representing negative values, which are calculated by inverting all bits, and then adding one. This will result in 0011 (inverse of the last 4 bytes), and then adding one of them will cause it to be 0100, which is a binary representation of 4.

Since the sign bit is negative, this results in -4

0
source

All Articles