How can I detect integer overflow on 32 bits int?(如何检测 32 位 int 上的整数溢出?)
问题描述
我知道这样的话题被问了好几次,但我的问题是关于完整的 32 位 int 的溢出.例如:
I know such topic was asked several times, but my question is about overflow on full 32 bits of int. For example:
11111111111111111111111111111111 +
00000000000000000000000000000001 =
00000000000000000000000000000000 //overflow!
我发现 topic 有类似的问题,但是算法并不完美.
I found topic with similar question about this, however the algorithm is not perfect.
11111111111111111111111111111111 +
00000000000000000000000000000000 =
00000000000000000000000000000000 //overflow!
有没有什么简单、快速、安全的检查方法?
Is there any simple, fast, safer way to check this ?
推荐答案
Math.addExact 溢出时抛出异常
从 Java 8 开始,数学类:
Math.addExact throws exception on overflow
Since Java 8 there is a set of methods in the Math class:
toIntExact(long)addExact(int,int)subtractExact(int,int)multiplyExact(int,int)
……以及长期版本.
这些方法中的每一个都会抛出 ArithmeticException 如果发生溢出.否则,如果它在范围内,它们会返回正确的结果.
Each of these methods throws ArithmeticException if overflow happens. Otherwise they return the proper result if it fits within the range.
加法示例:
int x = 2_000_000_000;
int y = 1_000_000_000;
try {
int result = Math.addExact(x, y);
System.out.println("The proper result is " + result);
} catch(ArithmeticException e) {
System.out.println("Sorry, " + e);
}
查看此在 IdeOne.com 上实时运行的代码.
对不起,java.lang.ArithmeticException:整数溢出
Sorry, java.lang.ArithmeticException: integer overflow
这篇关于如何检测 32 位 int 上的整数溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检测 32 位 int 上的整数溢出?
基础教程推荐
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- JPA惰性列表上的流 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 将 double 转换为 Int,向下舍入 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
