Consider the following Java code:
byte a = -64;
System.out.println(a << 1);
The output of this code is -128
I tried as follows to figure out why this is the output:
64 = 0 1000000 (the MSB is the sign bit)
-64= 1 1000000 (Tow's complement format)
Expected output after shifting: 1 0000000 (This is equal to 0, because the MSB is just a sign bit)
Please anyone explain what I am missing.
The >>> operator is the unsigned right bit-shift operator in Java. It effectively divides the operand by 2 to the power of the right operand, or just 2 here.
>> is arithmetic shift right, >>> is logical shift right. In an arithmetic shift, the sign bit is extended to preserve the signedness of the number. For example: -2 represented in 8 bits would be 11111110 (because the most significant bit has negative weight).
The left shift means that shift each of the bits in binary representation toward the left. For example, when we say left shift 5 or 101 by one position. We will shift each of the bits by one position towards the left. So after shifting the number 5 towards left by one position, the number obtained is 10 or 1010.
The two's complement representation of -128 is 10000000, thus your results are correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With