Multiplication of two ints overflowing to result in a negative number

前端 未结 5 1221
离开以前
离开以前 2020-12-01 21:27

Consider this snippet from the Java language specification.

class Test {
    public static void main(String[] args) {
        int i = 1000000;
        System         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 22:02

    Lets look at the binary:

    1000000 is 1111 0100 0010 0100 0000.
    1000000000000 is 1110 1000 1101 0100 1010 0101 0001 0000 0000 0000

    However, the first two sections of 4 bits won't fit in an int (since int is 32-bits wide in Java,) and so they are dropped, leaving only 1101 0100 1010 0101 0001 0000 0000 0000, which is -727379968.

    In other words, the result overflows for int, and you get what's left.

提交回复
热议问题