Java如何处理整数下溢和溢出以及如何检查它? [英] How does Java handle integer underflows and overflows and how would you check for it?

查看:174
本文介绍了Java如何处理整数下溢和溢出以及如何检查它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How does Java handle integer underflows and overflows?

从那开始,你会如何检查/测试这种情况发生?

Leading on from that, how would you check/test that this is occurring?

推荐答案

如果它溢出,它会回到最小值并从那里继续。如果它下溢,则返回最大值并继续从那里开始。

If it overflows, it goes back to the minimum value and continues from there. If it underflows, it goes back to the maximum value and continues from there.

您可以事先检查如下:

public static boolean willAdditionOverflow(int left, int right) {
    if (right < 0 && right != Integer.MIN_VALUE) {
        return willSubtractionOverflow(left, -right);
    } else {
        return (~(left ^ right) & (left ^ (left + right))) < 0;
    }
}

public static boolean willSubtractionOverflow(int left, int right) {
    if (right < 0) {
        return willAdditionOverflow(left, -right);
    } else {
        return ((left ^ right) & (left ^ (left - right))) < 0;
    }
}

(您可以替换 int by long long执行相同的检查

(you can substitute int by long to perform the same checks for long)

如果您认为这种情况可能经常发生,请考虑使用可以存储更大值的数据类型或对象,例如 long 或者 java.math.BigInteger中 。最后一个没有溢出,实际上,可用的JVM内存是限制。

If you think that this may occur more than often, then consider using a datatype or object which can store larger values, e.g. long or maybe java.math.BigInteger. The last one doesn't overflow, practically, the available JVM memory is the limit.

如果你碰巧在Java8已经可以使用新的 Math #addExact() Math#subtractExact() 将抛出<的方法溢出时code> ArithmeticException 。

If you happen to be on Java8 already, then you can make use of the new Math#addExact() and Math#subtractExact() methods which will throw an ArithmeticException on overflow.

public static boolean willAdditionOverflow(int left, int right) {
    try {
        Math.addExact(left, right);
        return false;
    } catch (ArithmeticException e) {
        return true;
    }
}

public static boolean willSubtractionOverflow(int left, int right) {
    try {
        Math.subtractExact(left, right);
        return false;
    } catch (ArithmeticException e) {
        return true;
    }
}

可以找到源代码这里这里

当然,您也可以立即使用它们而不是将它们隐藏在 boolean 实用程序方法中。

Of course, you could also just use them right away instead of hiding them in a boolean utility method.

这篇关于Java如何处理整数下溢和溢出以及如何检查它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆