My goal is to understand the two's complement.
10000111
in signed integer equals to -121
. However, if you bitwise AND it with 0xFF
in hexadecimal or 11111111
in decimal, it will equals to 135
.
In my view, this should not happen because the top byte 10000111
is identical to the result byte 10000111
10000111
AND 11111111
------------
10000111 = 135.
My expected result is the value should not change, which is equals to -121
.
My actual result is the value changes.
My guess is that, the 0xFF
is a unsigned bit
. Therefore, the signed bit 1
on the top byte and unsigned bit 1
on the lower byte will result in unsigned bit 1
. But... that could not be right.
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class WebSocketWorkerThreadTest {
@Test
void SignedToUnsignedInteger() {
byte signed = (byte) 0b10000111;
// If java uses unsigned integer, it should be 135. however, java uses signed integer. Therefore, the outputs will be -121
// 10000111
// ^
// the sign bit. If it exists then the value will be negative.
Assertions.assertEquals(-121, signed);
// 10000111
// 11111111
// --------
// 10000111
int unsigned = signed & 0xFF;
Assertions.assertEquals(135, unsigned);
}
}