Another way of thinking about this, is that in a 32 bit signed integers the leftmost digit represents one of two numbers:
0000000000000000000000000000000 represents 0
1000000000000000000000000000000 represents -2147483648
by definition. Everything else is an addition (added to) to this, so:
BINARY REPRESENTATION INT REPRESENTATION
1000000000000000000000000000000 plus -2147483648 plus
0111111111111111111111111111110 equals 2147483646 equals
1111111111111111111111111111110 -2
It would be helpful to think of the left-most (leading) bit as defining where you start counting from:
- if the leftmost bit is 0, you start counting from 0
- if the leftmost bit is 1, you start counting from -2147483648
The remaining 31 bits to the right of it define the integer value itself by making up a number (up to 2147483647 for 111 1111 1111 1111 1111 1111 1111
) that is added to the starting point.
Effectively then, signed integers wrap around. THey count up to a max value of about 2 billion, then instantly flip to -2 billion and count up to 0 again:
0111111111111111111111111111111
is 2147483647. If you add one to this you get:
1000000000000000000000000000000
which is either 2147483648 as an unsigned integer or -2147483648, and it is this way by definition. As you keep adding to any integer it approaches:
1111111111111111111111111111111
which is -1 as a signed integer, or 4294967295 as an unsigned
Ultimately, you should appreciate and understand that signed integers wrap around if you keep adding to them, but they instantly jump from the max positive to the min negative value in the middle:
0, 1, ... 2147483646, 2147483647, -2147483648, -2147483647, ... -2, -1
This is why your '11111111111111111111111111111110' is -2, as it's one less than the maximum binary representation (which represents -1 in signed int space)