This is not how you obtain a negative number from a positive number! Java uses two's complement.
In order to invert the sign of an int
(whether it is initally positive or negative), you do:
~val + 1
Same for long
s, byte
s and short
s.
The only number for which it doesn't work is 0x80000000, ie Integer.MIN_VALUE
, ie -2^31. But that is one of the characteristics of an n-bit two's complement representation: it can represent numbers ranging from -2^(n-1) up to 2^(n-1) - 1.
Let's take 1 as an example:
0x00000001 // i = 1
0xFFFFFFFE // ~i
0xFFFFFFFF // ~i + 1 == -1
0xFFFFFFFF // i = -1
0x00000000 // ~i
0x00000001 // ~i + 1 == 1