Java – multiplication overflow of two ints results in negative numbers
•
Java
Consider this fragment in the Java language specification
class Test { public static void main(String[] args) { int i = 1000000; System.out.println(i * i); long l = i; System.out.println(l * l); } }
Output is
-727379968 1000000000000
Why the result of (I * I) is - 727379968? Ideally, it should be 10000000000
I know that integer ranges from - 2147483648 to 2147483647 So obviously, 10000000000 is not in the given range
Why did the result become - 727379968?
Solution
Java (most computer architectures today) uses something called two's complexity arithmetic, which uses the highest bit of an integer to indicate that a number is negative If you multiply by two big numbers, you end up with such a big number, it sets the highest bit, and the result is negative
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码