How to judge integer overflow in Java
This article is about how to judge integer spillover in Java, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Solution
JDK8 has helped us to implement Math. I have to say that this method is found in StackOverflow, which is much better than some domestic forums.
Addition public static int addExact (int x, int y) {
Int r = x + y
/ / HD 2-12 Overflow iff both arguments have the opposite sign of the result
If ((x ^ r) & (y ^ r))
< 0) { throw new ArithmeticException("integer overflow"); } return r; } 减法 public static int subtractExact(int x, int y) { int r = x - y; // HD 2-12 Overflow iff the arguments have different signs and // the sign of the result is different than the sign of x if (((x ^ y) & (x ^ r)) < 0) { throw new ArithmeticException("integer overflow"); } return r; } 乘法public static int multiplyExact(int x, int y) { long r = (long)x * (long)y; if ((int)r != r) { throw new ArithmeticException("integer overflow"); } return (int)r; } 注意 long和int是不一样的 public static long multiplyExact(long x, long y) { long r = x * y; long ax = Math.abs(x); long ay = Math.abs(y); if (((ax | ay) >> > 31! = 0) {
/ / Some bits greater than 2 ^ 31 that might cause overflow
/ / Check the result using the divide operator
/ / and check for the special case of Long.MIN_VALUE *-1
If ((y! = 0) & & (r / y! = x)) | |
(X = = Long.MIN_VALUE & & y =-1) {
Throw new ArithmeticException ("long overflow")
}
}
Return r
}
The above is how to judge integer overflow in Java. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.