Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does bitshifting work in Java?

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?

like image 581
bentham Avatar asked Jul 22 '10 19:07

bentham


People also ask

How does right shift operator work in Java?

The signed right shift operator '>>' uses the sign bit to fill the trailing positions. For example, if the number is positive then 0 will be used to fill the trailing positions and if the number is negative then 1 will be used to fill the trailing positions. In Java, negative numbers are stored as 2's complement.

How does Bitshift work in Java?

The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator " >>> " shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.

How does left shift operator work in Java?

The left shift operator shifts all bits towards the left by a certain number of specified bits. It is denoted by << . As we can see from the image above, we have a 4-digit number. When we perform a 1 bit left shift operation on it, each individual bit is shifted to the left by 1 bit.

How does complement operator work in Java?

The bitwise complement operator is a unary operator (works on only one operand). It takes one number and inverts all bits of it.


1 Answers

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

like image 116
finnw Avatar answered Sep 17 '22 16:09

finnw