Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise operator x >> 1 and x >> 0 [duplicate]

Possible Duplicates:
What do these operators do?
>> in javascript

Can somebody please explain the bitwise operator >> 1?

example:

65 >> 1 = 32

and also when >> 0

what does it achieve in this example:

var size = (Math.random() * 100 >> 0) + 20;

like image 201
davivid Avatar asked May 19 '11 09:05

davivid


People also ask

What does 1 << 0 do in C?

1 << 0 is 1 shifted to the left by 0 positions, which is just 1.

How do bitwise operators multiply 2 numbers?

Multiply any Number with using Bitwise Operator in C++The left shift (<<) operator is used for the multiplication whereas the right shift (>>) is used for the division. The multiplication of two numbers x, y can be written as x * y = (x * 2) * (y / 2) if y is even else it's equal to x * y = (x * y) * (y / 2) + x.

What is the difference between the >> and >>> operators?

Difference between >> and >>> operator. Both >> and >>> are used to shift the bits towards the right. The difference is that the >> preserve the sign bit while the operator >>> does not preserve the sign bit. To preserve the sign bit, you need to add 0 in the MSB.

What does the operator >>> do?

The right shift operator ( >> ) returns the signed number represented by the result of performing a sign-extending shift of the binary representation of the first operand (evaluated as a two's complement bit string) to the right by the number of bits, modulo 32, specified in the second operand.


2 Answers

var size = (Math.random() * 100 >> 0) + 20;

>> 0 in the above example is used to eliminate the fractional portion, as follows:

  1. Math.random() returns a number between 0 and 0.99999999...
  2. This number multiplied by 100 gives you another number between 0 and 99.999999...
  3. This number is right shifted 0 times. The number is implicitly cast to an integer for the shift operation; right shifting 0 times does not have any effect on the value of the resulting integer. You thus end up with an integer between 0 and 99. Note that you could have used the Math.floor() function instead of >> 0.
  4. Add 20 to the integer, the result is an integer between 20 and 119.
like image 85
Salman A Avatar answered Oct 08 '22 02:10

Salman A


Bitwise operator >> means shift right.
It moves the binary value to the right (and removes the right-most bit).

65 >> 1 in binary is:

1000001 >> 1 = 100000 = 32

It effectively divides the number into 2 and drops the remainder.

like image 29
Yochai Timmer Avatar answered Oct 08 '22 02:10

Yochai Timmer