Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java shift operator

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.

like image 839
siva636 Avatar asked Feb 09 '12 07:02

siva636


People also ask

What is the use of >>> in Java?

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.

What is the difference between >> and >>> in Java?

>> 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).

How do you perform a left shift in Java?

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.


1 Answers

The two's complement representation of -128 is 10000000, thus your results are correct.

like image 128
Thomas Avatar answered Oct 13 '22 20:10

Thomas