An int
has a range from -231 to 231-1 , while the datatype itself takes 32 bytes. The most significant bit, bit 32, is used as the sign bit.
Now, if you could use this bit as a part of the 'absolute value' of the number, the range would go from 0 to 232. This would make the int
unsigned, but the Java datatype is signed. Hence, this would not be possible, unless you would move to a datatype that can hold the 32 bits without them affecting the sign bit.
232 = 1111 1111 1111 1111 1111 1111 1111 1111
Now, to move it to the next larger datatype long, which can hold 64 bits, 63 bits to represent the absolute value and the most significant bit as the sign bit. The exact same number would look like this.
232 = 0000 0000 0000 0000 0000 0000 0000 0000 1111 1111 1111 1111 1111 1111 1111 1111
0xffffffffL = 0000 0000 0000 0000 0000 0000 0000 0000 1111 1111 1111 1111 1111 1111 1111 1111
Now, to look at an int
value (try this Integer.toBinaryString(-2);
). Say, you have some int
like -2. In binary, it is represented as
1111 1111 1111 1111 1111 1111 1111 1110
"and" this with 0xffffffffL [the L
at the end signifies it to be a long
] [f
in hex is 1111
in binary; 8 f's, so 8 1111
s] (Try this Long.toBinaryString(0xffffffffL);
)
0000 0000 0000 0000 0000 0000 0000 0000 1111 1111 1111 1111 1111 1111 1111 1111
And you get,
0000 0000 0000 0000 0000 0000 0000 0000 1111 1111 1111 1111 1111 1111 1111 1110
which happens to be 4294967294 = 232 - 2. Just as expected. :)