How can I detect integer overflow on 32 bits int?

2020-02-09 00:31发布

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!

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 ?

5条回答
【Aperson】
2楼-- · 2020-02-09 00:37
long test = (long)x+y;
if (test > Integer.MAX_VALUE || test < Integer.MIN_VALUE)
   // Overflow!
查看更多
一夜七次
3楼-- · 2020-02-09 00:42

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

查看更多
smile是对你的礼貌
4楼-- · 2020-02-09 00:44

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.

查看更多
▲ chillily
5楼-- · 2020-02-09 00:47

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;
}
查看更多
混吃等死
6楼-- · 2020-02-09 01:04

Math.addExact throws exception on overflow

Since Java 8 there is a set of methods in the Math class:

…and versions for long as well.

Each of these methods throws ArithmeticException if overflow happens. Otherwise they return the proper result if it fits within the range.

Example of addition:

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);
}

See this code run live at IdeOne.com.

Sorry, java.lang.ArithmeticException: integer overflow

查看更多
登录 后发表回答