1

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 

  • What is this called?
  • What does this do?
  • Community
    • 1
    • 1
    DMin
    • 8,279
    • 9
    • 41
    • 61

    2 Answers2

    4

    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.

    Community
    • 1
    • 1
    Claudiu
    • 206,738
    • 150
    • 445
    • 651
    1

    It's the bitwise left shift operator.

    a << b will shift b bits to the left of the binary representation of a.

    João Silva
    • 81,431
    • 26
    • 144
    • 151