Multiplication of two ints overflowing to result in a negative number(两个整数相乘溢出导致负数)
问题描述
考虑一下 Java 语言规范中的这段代码.
Consider this snippet from 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);
}
}
输出是
-727379968
1000000000000
为什么 (i*i)
的结果是 -727379968
?理想情况下应该是 1000000000000.
Why is the result -727379968
for (i*i)
? Ideally it should be 1000000000000.
我知道 Integer 的范围是从 –2147483648 到 2147483647.所以显然 1000000000000不在给定范围内.
I know the range of Integer is from –2147483648 to 2147483647. so obviously 1000000000000 is not in the given range.
为什么结果会变成-727379968
?
推荐答案
Java(就像现在的大多数计算机架构一样)使用一种叫做 二进制补码算法,它使用整数的最高有效位来表示一个数字是否为负数.如果你将两个大数相乘,你会得到一个大到设置最高位的数,结果是负数.
Java (like most computer architectures these days) uses something called two's complement arithmetic, which uses the most significant bit of an integer to signify that a number is negative. If you multiply two big numbers, you end up with a number that's so big it sets that highest bit, and the result ends up negative.
这篇关于两个整数相乘溢出导致负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:两个整数相乘溢出导致负数


- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01