1

Possible Duplicate:
>> in javascript

I'm going through some code and I ran into 2 weird operators: >> and <<, in the form of 2<<3 and 442132132>>546542132.

I deduced that x<<y means x times 2 in the power of y. Meaning, 4<<3 is 4*(Math.pow(2,3)), which is 32, but I couldn't find what x>>y means.

I know it usually returns 0 for small numbers, but when high numbers are involved, the result is usually a small number.

Community
  • 1
  • 1
Dan
  • 872
  • 10
  • 24
  • 1
    duplicate of http://stackoverflow.com/questions/4437169/in-javascript and http://stackoverflow.com/questions/4535328/what-do-these-operators-do – Marek Sebera Sep 11 '11 at 12:30

5 Answers5

6

From Mozilla:

Left shift a << b Shifts a in binary representation b (< 32) bits to the left, shifting in zeros from the right.
Sign-propagating right shift a >> b Shifts a in binary representation b (< 32) bits to the right, discarding bits shifted off.

442132132>>546542132 seems excessive for a number that is only 32 bits wide.

Dennis
  • 32,200
  • 11
  • 64
  • 79
6

The >> operator bit-shifts the left value by the right one.

a >> b is equivalent to parseInt(a / Math.pow(2, b)).

For example:

 1 >> 0 == 1
 4 >> 1 == 2
 6 >> 1 == 3
42 >> 3 == 5
0x120 >> 4 == 0x12
0x129 >> 4 == 0x12
0x12f >> 4 == 0x12
0x130 >> 4 == 0x13
phihag
  • 278,196
  • 72
  • 453
  • 469
1

<< is the bitwise left operator, and >> is the bitwise right operator.

These shift the value on one side of the equation by the value on the other.

Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162
1

It's converted into binary, and then moved to the left or the right. Like 2 << 3:

0000010

becomes:

0010000

Or 16 if you convert it back.

>> is the other way round: (16 >> 3) === 2.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
1

These are the binary shift operators. A

As you know, numbers are represented in binary in computers (6 = 110 , 9 = 1001, etc.)

A left bit shift "<<" shifts the binary digits to the left. For instance, 6 << 2 shifts 6 (i.e. 110) two binary digits.

Also note that in a 32-bit environment, 32-bits would be used to represent an integer, so 6 would be:

0000 0000 0000 0000 0000 0000 0000 0110

6 << 2 (6 shifted 2 to the left):

0000 0000 0000 0000 0000 0000 0001 1000

6 >> 2 (6 shifted 2 to the right):

0000 0000 0000 0000 0000 0000 0000 0001

WaelJ
  • 2,942
  • 4
  • 22
  • 28