日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

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

發布時間:2023/12/10 java 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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.

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.

總結

以上是生活随笔為你收集整理的java 整数溢出检测,Java如何处理整数下溢和溢出以及如何检查它?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。