• admin
  • 108
  • 2025-11-06 05:27:08

整数溢出

int类型一般占4个字节,故取值范围 -2^31 ~ 2^31-1,对于无符号另当别论,我们的讨论建立在以补码形式存储的带符号整数

-上溢

存储数值超过了整形数值2^31-1,导致数据向上溢出

-下溢

整数数值小于了-2^31,导致数值向下溢出

加法溢出

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;

}

另一种写法:

if(num1>Integer.MAX_VALUE-num2)

System.out.println("num1+num2上溢出");

if(num1

System.out.println("num1+num2下溢出");

减法溢出

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;

}

原理其实很简单。只有两个正数或者两个负数相加的时候才会溢出,一正一负是不会溢出的。并且,溢出后得到的结果一定是与原值的符号相反的。

​ 借用这个原理,(x ^ r) & (y ^ r)将用运算符算出来的r与x和y分别异或。异或的规则是同0异1。我们只看符号位,如果符号位不同,那么两个括号得到的都是1。而与运算又是只有1 & 1才是1,有一个为0都是0。因此,一旦溢出,无论是正溢出负溢出,(x ^ r) & (y ^ r)计算出的结果都应该小于0

public static void main(String[] args) {

int c = Integer.MAX_VALUE + Integer.MAX_VALUE;

long c1 = Integer.MIN_VALUE + Integer.MIN_VALUE;

System.out.println(c); //-2 = 两正数相加,溢出最大到-2

System.out.println(c1); //0 = 两负数相加,溢出最大到0

// 两者符号不同

}

乘法溢出

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;

}

注意这个坑

public static void main(String[] args) {

int a = 964632435;

int c = a * 10;

long c1 = a * 10; // 相当于(long)(a + 10) = (long)c:两个int类型运算,结果仍然是int,当 = 时,自动提升类型

long c2 = (long) (a * 10);

long c3 = (long) c;

System.out.println(c); //1056389758

System.out.println(c1); //1056389758

System.out.println(c2); //1056389758

System.out.println(c3); //1056389758

System.out.println();

long c4 = (long)a * (long)10;

long c5 = (long)a *10; // int与long运算,int自动类型提升

System.out.println(c4); //9646324350

System.out.println(c5); //9646324350

System.out.println((int)c5);

}

注意 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;

}