Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a bitwise shift (left or right) do and what is it used for?

I've seen the operators >> and << in various code that I've looked at (none of which I actually understood), but I'm just wondering what they actually do and what some practical uses of them are.

If the shifts are like x * 2 and x / 2, what is the real difference from actually using the * and / operators? Is there a performance difference?

like image 682
The.Anti.9 Avatar asked Jun 17 '11 12:06

The.Anti.9


People also ask

How do I use bitwise right shift?

Application of Bitwise Right Shift Operator If I shift 14 by 2 position to the right, output will be 14 / 4 = 3. i.e 14/4 =3.5 since it's an integer, fractional part will not be considered. In general, if we shift a number by n times to right, the output will be number / (2n) .

What is bitwise Shift used for?

Bitwise Right Shift Operator. The bitwise right shift operator is very similar to the left shift operator. Instead of shifting the bits to the left, believe it or not, it shifts the bits to the right.

Why we use left shift?

We use the left shift operator to shift the bits of available values to the left. It does so by adding zeros to the right side of the value in the empty spaces that get created due to shifting.


2 Answers

Here is an applet where you can exercise some bit-operations, including shifting.

You have a collection of bits, and you move some of them beyond their bounds:

1111 1110 << 2 1111 1000 

It is filled from the right with fresh zeros. :)

0001 1111 >> 3 0000 0011 

Filled from the left. A special case is the leading 1. It often indicates a negative value - depending on the language and datatype. So often it is wanted, that if you shift right, the first bit stays as it is.

1100 1100 >> 1 1110 0110 

And it is conserved over multiple shifts:

1100 1100 >> 2 1111 0011 

If you don't want the first bit to be preserved, you use (in Java, Scala, C++, C as far as I know, and maybe more) a triple-sign-operator:

1100 1100 >>> 1 0110 0110 

There isn't any equivalent in the other direction, because it doesn't make any sense - maybe in your very special context, but not in general.

Mathematically, a left-shift is a *=2, 2 left-shifts is a *=4 and so on. A right-shift is a /= 2 and so on.

like image 185
user unknown Avatar answered Oct 12 '22 15:10

user unknown


Left bit shifting to multiply by any power of two and right bit shifting to divide by any power of two.

For example, x = x * 2; can also be written as x<<1 or x = x*8 can be written as x<<3 (since 2 to the power of 3 is 8). Similarly x = x / 2; is x>>1 and so on.

like image 24
Nitish Avatar answered Oct 12 '22 16:10

Nitish