3

I was going through some code for prime numbers on Stack and found this.

I tried experimenting with this for sometime and figured this :

var i = 5;
var j = 0;

If i write j = i << 1, all it does is assigns (i * 2) ie - 10 in this case to j

If i write j = i << 2, (i * 2) * 2 ie - 10 * 2 .....and so on.

Now i have a doubt what actually this operator does ?

I tried googling this, but did not find any straight solution to this.

Janak
  • 4,986
  • 4
  • 27
  • 45

3 Answers3

6

Those are Bitwise Operators in Javascript.

Bitwise operators treat their operands as a sequence of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

Left Shift Operator :

a << b : Shifts a in binary representation b (< 32) bits to the left, shifting in zeros from the right.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • I want to add, they do the same thing in PHP. – David Bélanger Jun 05 '13 at 12:44
  • It's also worth noting that the left operand is converted an int32, and the right operand is converted to a uint32 before the operation is performed, per the [spec](http://es5.github.io/#x11.7.1). – Peter Olson Jun 05 '13 at 12:51
1

<< is the left shift operator. Each bit would shift left the number of times specified. Example: n<<2 would bitwise shift n 2 times, adding zeros to the right.

n=4  // 0000 0000 0000 0100
n<<2 //<= 0000 0000 0001 0000 - Value is 16
karthikr
  • 97,368
  • 26
  • 197
  • 188
0

The << operator[ES5 spec] is the left bit shift operator. It takes the number on the left and shifts the bits as many places as the number on the right. i << 2, for example, will shift the digits of i to the left 2 places.

var i = 5;  // i: 0000 0000 0000 0101
i = i << 2; // i: 0000 0000 0001 0100
Peter Olson
  • 139,199
  • 49
  • 202
  • 242