Math.addExact() function understanding

Math.addExact(), a new method added in Jdk1.8, to determine whether the addition of two numbers overflows, the source code is as follows:

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;
}

First think about what is overflow?

  • Negative makes positive
  • Positive and negative

These two situations have a common feature: that isThe return value and the sign of the input parameter are not the same, In fact, the code is judged like this, and the comments are also introduced like this~.

Bit operation

  • ^ XOR operation: the same is 0, the difference is 1. 1 ^ 1 = 0, 1 ^ 0 = 1, 0 ^ 1 = 1, 0 ^ 0 = 0
  • & Operation: Both are 1 and it is 1, otherwise it is 0. 1 & 1 = 1, all others are 0.

Code interpretation

  • The first binary digit of a positive number in a computer is 0, and the first binary digit of a negative number is 1. According to this characteristic, if an overflow occurs, the first binary bit of r and x and y must be different.
  • If overflow, the first bit of the binary result of (x ^ r) and (y ^ r) must be 1, (x ^ r) and (y ^ r) are both negative numbers, naturally (x ^ r) & (y ^ r) is also negative. So as long as ((x ^ r) & (y ^ r)) <0, an overflow occurs.

Guess you like

Origin blog.csdn.net/qq_27007509/article/details/112384366