When I constructed the mask to get the most significant bit in the 2's complement format, I have found the unexpected behavior.
To check whether the most significant bit is active or not in the signed 8-bit number, I could get the bit as follows.
byte value = -1;
long byteSignMask = 0b1000_0000;
value & byteSignMask;
The result is identical regardless I use 0b1000_0000
or 1L << 7
for byteSignMask
. Actually following code passes.
long byteSign1 = 1L << 7;
long byteSign2 = 0b1000_0000;
// OK
assertEquals(byteSign1, byteSign2);
But I did for the int type; similarly, the outcome was expected.
long intSign1 = 1L << 31;
long intSign2 = 0b1000_0000_0000_0000_0000_0000_0000_0000;
// Fail: expected:<2147483648> but was:<-2147483648>
assertEquals(intSign1, intSign2);
Actually, they are different.
// intSign1 = 10000000000000000000000000000000
System.out.println("intSign1 = " + Long.toBinaryString(intSign1));
// intSign2 = 1111111111111111111111111111111110000000000000000000000000000000
System.out.println("intSign2 = " + Long.toBinaryString(intSign2));
It looks like the literal mask of the integer (intSign1
) is left-padded with 1, while the shift operation does not cause such an effect.
Why is the integer expressed by the binary literal automatically left-padded with 1? Is there any official documentation describing this behavior?