如何在32位int上检测整数溢出?

ash*_*hur 25 java integer bit-manipulation integer-overflow integer-arithmetic

我知道这样的话题被问过好几次,但我的问题是关于整个32位int的溢出.例如:

  11111111111111111111111111111111 +
  00000000000000000000000000000001 =
  00000000000000000000000000000000   //overflow!
Run Code Online (Sandbox Code Playgroud)

我找到了类似问题的主题,但算法并不完美.

  11111111111111111111111111111111 +
  00000000000000000000000000000000 =
  00000000000000000000000000000000  //overflow!
Run Code Online (Sandbox Code Playgroud)

有没有简单快捷的方法来检查这个?

小智 41

从Java 8开始,Math类中有一组方法: toIntExact(long),addExact(int,int),subtractExact(int,int),multiplyExact(int,int),以及long版本.如果发生溢出,它们会抛出ArithmeticException,如果它适合该范围,它们将返回正确的结果.

添加示例:

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);
}
Run Code Online (Sandbox Code Playgroud)


Tim*_*m B 14

long test = (long)x+y;
if (test > Integer.MAX_VALUE || test < Integer.MIN_VALUE)
   // Overflow!
Run Code Online (Sandbox Code Playgroud)

  • 你说的不对。X被强制转换为加法(优先级)之前很久。long + int将int转换为long,最后得到long + long。因此,整个操作以64位精度完成。 (3认同)

Vus*_*sal 8

试试这种方式:

boolean isOverflow(int left, int right) {
    return right > 0
            ? Integer.MAX_VALUE - right < left
            : Integer.MIN_VALUE - right > left;
}
Run Code Online (Sandbox Code Playgroud)

来自:https://wiki.sei.cmu.edu/confluence/display/java/NUM00-J.+Detect+or+prevent+integer+overflow