問題描述
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.
您可以按如下方式預先檢查:
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;
}
}
(您可以將 int
替換為 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()
方法會拋出 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;
}
}
源碼可以找到這里 和 這里分別.
The source code can be found here and here respectively.
當然,您也可以直接使用它們,而不是將它們隱藏在 boolean
實用程序方法中.
Of course, you could also just use them right away instead of hiding them in a boolean
utility method.
這篇關于Java 如何處理整數下溢和上溢以及如何檢查它?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!