I’m going to answer these in reverse, as it’ll make more sense that way.
All the other values have a 1 as their left most bit.
Not exactly. This is true if we simply write out the values, but it is false if we look at each number in the context of it being a 4-byte (32-bit) value. For example:
i=1 1073741816 = 111111111111111111111111111000 (30 bits to store number)
If we view the entirety of the 32-bit space this number can occupy, we see this:
Here we can see the entirety of the 32-bit space, with the binary representation of your number in the bits highlighted in green. There are two leading zeroes at the start of the number, in yellow. The left-most bit is a zero, hence the number is positive.
- Why does it become negative?
In Java, the
int type is signed. Everything to a computer comes down to bits -
0. There is no concept of a negative sign
-, so if the computer needs to be aware of negative values we need some way of telling it about them.
Java is seeing
-32 as the following.
As the most significant (left most) bit is a
1, the number is a negative. This is by convention; the computer does everything in
0s - there’s no concept of encoding a negative sign, so a bit is reserved to indicate this instead.
- Why does it become -32 in particular?
Java uses a method of representing negative numbers which is called “Two’s complement”. I’ll link to a fuller description of that at the end, but for now I’ll just cover the basics.
Let's change 32 to -32 by converting to Twos complement representation
00000000000000000000000000100000 # 32 in binary
11111111111111111111111111011111 # invert (flip) each bit.
11111111111111111111111111100000 # add one.
The value represented by
11111111111111111111111111100000 is essentially the same as taking
-(2^31) - the left-most bit - and then adding the positive value of each subsequent
1, like so:
+ 1073741824 + 536870912 + 268435456 + 134217728 + 67108864 + 33554432 + 16777216
+ 8388608 + 4194304 + 2097152 + 1048576 + 524288 + 262144 + 131072 + 65536 + 32768
+ 16384 + 8192 + 4096 + 2048 + 1024 + 512 + 256 + 128 + 64 + 32
You end up with
Hope that clears it up a bit.
Also, here’s the link for more info on Two’s complement representation.