How does bitshifting work in Java?

bentham picture bentham · Jul 22, 2010 · Viewed 117.2k times · Source

I have this statement:

Assume the bit value of byte x is 00101011. what is the result of x>>2?

How can I program it and can someone explain me what is doing?

Answer

finnw picture finnw · Jul 22, 2010

Firstly, you can not shift a byte in java, you can only shift an int or a long. So the byte will undergo promotion first, e.g.

00101011 -> 00000000000000000000000000101011

or

11010100 -> 11111111111111111111111111010100

Now, x >> N means (if you view it as a string of binary digits):

  • The rightmost N bits are discarded
  • The leftmost bit is replicated as many times as necessary to pad the result to the original size (32 or 64 bits), e.g.

00000000000000000000000000101011 >> 2 -> 00000000000000000000000000001010

11111111111111111111111111010100 >> 2 -> 11111111111111111111111111110101