当前位置:   article > 正文

java 整数溢出检测,Java如何处理整数下溢和溢出以及如何检查它?

java cert_03_00检测和避免整数溢出

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.

You can check that beforehand as follows:

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;

}

}

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

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.

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;

}

}

The source code can be found here and here respectively.

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/141895
推荐阅读
相关标签
  

闽ICP备14008679号