How can I detect integer overflow on 32 bits int?

狂风中的少年 提交于 2019-11-28 23:09:55

Since Java 8 there is a set of methods in the Math class: toIntExact(long), addExact(int,int), subtractExact(int,int), multiplyExact(int,int), and versions for long as well. They throw ArithmeticException if overflow happens, they return the proper result if it fits within the range.

Example of addition:

int x = 2000000000;
int y = 1000000000;
try {
    int result = Math.addExact(x, y);
    System.out.println("The proper result is " + result);
} catch(ArithmeticException e) {
    System.out.println("Sorry, " + e);
}
long test = (long)x+y;
if (test > Integer.MAX_VALUE || test < Integer.MIN_VALUE)
   // Overflow!

Try this way:

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

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

Overflow can be detected by a logical expression of the most significant bit of the two operands and the (truncated) result (I took the logical expression from the MC68030 manual):

/**
 * Add two int's with overflow detection (r = s + d)
 */
public static int add(int s, int d) throws ArithmeticException {
    int r = s + d;
    if (((s & d & ~r) | (~s & ~d & r)) < 0)
        throw new ArithmeticException("int overflow add(" + s + ", " + d + ")");
    return r;
}

The most intuitive method I can think of: calculate the sum (or difference) as a long, then convert that sum to an int and see if its value has changed.

long longSum = (long) a + b;
int sum = (int) longSum;
if (sum == longSum) {
    // sum contains the correct result
} else {
    // overflow/underflow
}

Remember that on modern 64 bit processors, working with longs is no less efficient than working with ints (the opposite may be true). So if you have a choice between checking for overflows or using longs, go for the latter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!