Why does the negative of Integer.MIN_VALUE give the same value? [duplicate]

人盡茶涼 提交于 2019-12-01 03:53:02
dasblinkenlight

What kind of bit-wise operations are happening internally?

Java uses two's complement representation of signed numbers. Therefore, the change of sign operation, consists of two steps:

  1. Inverting the bits of the original value, and
  2. Adding 1 to the result.

2147483648's representation is shown below:

10000000000000000000000000000000

Inverting it produces

01111111111111111111111111111111

Adding 1 makes it the same number again, i.e.

10000000000000000000000000000000

due to integer overflow.

When you negate -2147483648, it resolves to 2147483648, which exceeds the Integer.MAX_VALUE with 1. Then the value overflows to Integer.MIN_VALUE again.

From the JLS:

The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers.

So, every unary operation done on an integer will actually be applied on the two's complement representation of the number. When the Integer.MAX_VALUE is reached it will consist of a leading 0 and 31 1 bits. Adding 1 would make it a number with a leading 1 and 31 trailing 0s, which is actually the two's complement representation of Integer.MIN_VALUE.

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