Why does this multiplication integer overflow result in zero?

扶醉桌前 提交于 2019-11-27 06:58:44

问题


After answering this question, I was confused about why the overflowing integer in this code resulted in 0 instead of a negative number. It's strange, why such an exact number? Why 0?

public class IntegerOverflow {
  public static void main(String[] args) {
    int x = 10;

    int i = 0;
    for (i = 0; i <= 5; i++)
    {
      x = x * x;
      System.out.println(x);
    }
  }
}

Output:

100
10000
100000000
1874919424
0
0

回答1:


This will only happen if the starting value of x is even.

According to the JLS §15.17.1:

If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.

This is made much more obvious if we print the numbers in binary format instead of in decimal:

public class IntegerOverflow {
  public static void main(String[] args) {
    int x = 10;

    int i = 0;
    for (i = 0; i <= 5; i++)
    {
      x *= x;
      System.out.println(Integer.toBinaryString(x));
    }
  }
}

Output:

1100100
10011100010000
101111101011110000100000000
1101111110000010000000000000000
0
0

As you can see, each time we square, we double the number of zero bits. Since only the low order bits are saved, doubling the zeroes every time will eventually result in zero. Notice that we do not see these trailing zeroes if the starting value for x is odd. It will result, instead, it will result in seemingly unrelated numbers like overflow usually does.

public class IntegerOverflow {
  public static void main(String[] args) {
    int x = 11;

    int i = 0;
    for (i = 0; i <= 5; i++)
    {
      x *= x;
      System.out.format("%-12d\t%s%n", x, Integer.toBinaryString(x));
    }
  }
}

Output:

121             1111001
14641           11100100110001
214358881       1100110001101101101101100001
772479681       101110000010110001101011000001
-1419655807     10101011011000011100010110000001
-1709061375     10011010001000011100101100000001


来源:https://stackoverflow.com/questions/32042346/why-does-this-multiplication-integer-overflow-result-in-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!