我知道这样的话题被问了好几次,但我的问题是关于完整的 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 overflowSince 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 上的整数溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
return 语句之前的局部变量,这有关系吗?Local variables before return statements, does it matter?(return 语句之前的局部变量,这有关系吗?)
如何将整数转换为整数?How to convert Integer to int?(如何将整数转换为整数?)
如何在给定范围内创建一个随机打乱数字的 intHow do I create an int array with randomly shuffled numbers in a given range(如何在给定范围内创建一个随机打乱数字的 int 数组)
java的行为不一致==Inconsistent behavior on java#39;s ==(java的行为不一致==)
为什么 Java 能够将 0xff000000 存储为 int?Why is Java able to store 0xff000000 as an int?(为什么 Java 能够将 0xff000000 存储为 int?)
意外结果导致长/整数除法Unexpected result in long/int division(意外结果导致长/整数除法)