问题
I have the following rather straight forward bit-wise operation
final int mask = ((1 << 31) - 1);
However, I'm really can't figure out why, Android Studio (IntelliJ) IDE will give me Numeric Overflow
warning
I did a quick run in desktop
public static void main(String[] args) {
final int mask = ((1 << 31) - 1);
System.out.println(mask); // 2147483647
System.out.println(Integer.MAX_VALUE); // 2147483647
}
It seems fine to me. However, I was puzzling, why IDE gives me such warning?
回答1:
It seems that it was an issue in IntelliJ 2018.1. Here is explanation,
IDEA-182699 Numeric overflow: add an option to ignore if left bitwise shift result makes number negative - Its question
The compiler gets 1
as int
. What about?
final int mask = (int)((1L << 31) - 1);
Mathematically,
1000 0000 0000 0000 0000 0000 0000 0000 (1 << 31)
1111 1111 1111 1111 1111 1111 1111 1111 (-1)
-----------------------------------------
1 0111 1111 1111 1111 1111 1111 1111 1111 +
^
0111 1111 1111 1111 1111 1111 1111 1111 (truncate)
回答2:
You shifted into the sign bit: 1<<31 = 231 and Integer.MAX_VALUE = 231 - 1. Hence there is (sign) overflow, you actually got Integer.MIN_VALUE. Further subtracting 1 can be called an overflow (carry) too, and probably triggered the error.
来源:https://stackoverflow.com/questions/51651590/why-the-following-bitwise-operation-will-generate-a-numeric-overflow