How is 0x80000000 equated to -2147483648 in java?

前端 未结 2 1979
天命终不由人
天命终不由人 2020-12-19 04:38

Taking the binary of 0x80000000 we get

1000 0000 0000 0000 0000 0000 0000 0000

How does this equate to -2147483648

相关标签:
2条回答
  • 2020-12-19 05:21

    This is the case when there is overflow, with respect to the range of a data type. Here is an example that I can share.

    int number = 0x80; // 0x80 is hexadecimal for 128 (decimal)
    byte castedNumber = (byte)(number); // On casting, there is overflow,as byte ranges from -128 to 127 (inclusive).
    System.out.println(castedNumber); //Output is -128.
    
    0 讨论(0)
  • 2020-12-19 05:26

    This is what happens with signed integer overflow, basically.

    It's simpler to take byte as an example. A byte value is always in the range -128 to 127 (inclusive). So if you have a value of 127 (which is 0x7f) if you add 1, you get -128. That's also what you get if you cast 128 (0x80) to byte:

    int x = 0x80; // 128
    byte y = (byte) x; // -128
    

    Overflow (in 2s complement integer representations) always goes from the highest expressible number to the lowest one.

    For unsigned types, the highest value overflows to 0 (which is again the lowest expressible number). This is harder to show in Java as the only unsigned type is char:

    char x = (char) 0xffff;
    x++;
    System.out.println((int) x); // 0
    
    0 讨论(0)
提交回复
热议问题