bentham bentham - 1 year ago 93
Java Question

How does bitshifting work in Java?

I have this statement:

Assume the bit value of byte
is 00101011. what is the result of

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

Answer Source

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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download