Java如何处理整数下溢和溢出?

在此基础上,你将如何检查/测试这种情况的发生?


当前回答

我认为你应该使用这样的东西,它被称为Upcasting:

public int multiplyBy2(int x) throws ArithmeticException {
    long result = 2 * (long) x;    
    if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE){
        throw new ArithmeticException("Integer overflow");
    }
    return (int) result;
}

你可以在这里进一步阅读: 检测或防止整数溢出

这是相当可靠的来源。

其他回答

默认情况下,Java的int和long数学在溢出和下溢时默默地环绕。(根据JLS 4.2.2,对其他整数类型的整数操作是通过首先将操作数提升为int或long来执行的。)

从Java 8开始,Java .lang. math为执行命名操作的int和long参数提供了addExact、subtractExact、multiplyExact、incrementExact、decrementExact和negateExact静态方法,并在溢出时抛出arithmeexception。(没有divideExact方法——您必须自己检查一个特殊情况(MIN_VALUE / -1)。)

从Java 8开始,Java .lang. math还提供了toIntExact来将long类型转换为int类型,如果long类型的值不适合int类型,则抛出arithmeexception。这对于例如使用未检查的long math计算int的和,然后在最后使用toIntExact强制转换为int很有用(但要注意不要让你的和溢出)。

If you're still using an older version of Java, Google Guava provides IntMath and LongMath static methods for checked addition, subtraction, multiplication and exponentiation (throwing on overflow). These classes also provide methods to compute factorials and binomial coefficients that return MAX_VALUE on overflow (which is less convenient to check). Guava's primitive utility classes, SignedBytes, UnsignedBytes, Shorts and Ints, provide checkedCast methods for narrowing larger types (throwing IllegalArgumentException on under/overflow, not ArithmeticException), as well as saturatingCast methods that return MIN_VALUE or MAX_VALUE on overflow.

我自己也遇到了这个问题,下面是我的解决方案(包括乘法和加法):

static boolean wouldOverflowOccurwhenMultiplying(int a, int b) {
    // If either a or b are Integer.MIN_VALUE, then multiplying by anything other than 0 or 1 will result in overflow
    if (a == 0 || b == 0) {
        return false;
    } else if (a > 0 && b > 0) { // both positive, non zero
        return a > Integer.MAX_VALUE / b;
    } else if (b < 0 && a < 0) { // both negative, non zero
        return a < Integer.MAX_VALUE / b;
    } else { // exactly one of a,b is negative and one is positive, neither are zero
        if (b > 0) { // this last if statements protects against Integer.MIN_VALUE / -1, which in itself causes overflow.
            return a < Integer.MIN_VALUE / b;
        } else { // a > 0
            return b < Integer.MIN_VALUE / a;
        }
    }
}

boolean wouldOverflowOccurWhenAdding(int a, int b) {
    if (a > 0 && b > 0) {
        return a > Integer.MAX_VALUE - b;
    } else if (a < 0 && b < 0) {
        return a < Integer.MIN_VALUE - b;
    }
    return false;
}

如果有错误或者可以简化,请随意纠正。我已经用乘法法做了一些测试,大部分是边缘情况,但它仍然可能是错误的。

有一种情况,上面没有提到:

int res = 1;
while (res != 0) {
    res *= 2;

}
System.out.println(res);

会产生:

0

本案例讨论如下: 整数溢出产生零。

我想这应该没问题。

static boolean addWillOverFlow(int a, int b) {
    return (Integer.signum(a) == Integer.signum(b)) && 
            (Integer.signum(a) != Integer.signum(a+b)); 
}

它什么都不做——只是发生了under/overflow。

“-1”是溢出计算的结果,与任何其他信息产生的“-1”没有区别。因此,您不能通过某些状态或仅仅检查一个值来判断它是否溢出。

但是为了避免溢出,你可以聪明地进行计算,如果这很重要的话,或者至少知道什么时候会发生溢出。你的情况如何?