what does << do in javascript
Possible Duplicate:
Absolute Beginner's Guide to Bit Shifting?
What is the JavaScript >>> operator and how do you use it?
I came across <<
while reading some code.
1<<1 //2
2<<1 //4
3<<1 //6
3<<2 //12
Taken from this answer:
Left shift (<<)
Integers are stored, in memory, as a series of bits. For example, the number 6 stored as a 32-bit int
would be:
00000000 00000000 00000000 00000110
Shifting this bit pattern to the left one position ( 6 << 1
) would result in the number 12:
00000000 00000000 00000000 00001100
As you can see, the digits have shifted to the left by one position, and the last digit on the right is filled with a zero. You might also note that shifting left is equivalent to multiplication by powers of 2. So 6 << 1
is equivalent to 6 * 2
, and 6 << 3
is equivalent to 6 * 8
. A good optimizing compiler will substitute shifts for multiplications when possible.
Non-circular shifting
Please note that these are not circular shifts. Shifting this value to the left by one position ( 3,758,096,384 << 1
):
11100000 00000000 00000000 00000000
results in 3,221,225,472:
11000000 00000000 00000000 00000000
The digit that gets shifted "off the end" is lost. It does not wrap around.
It's the bitwise left shift operator.
a << b
will shift b
bits to the left of the binary representation of a
.
上一篇: C#.net按位左移操作。
下一篇: “在JavaScript中做什么?