PHP Operator <<

27,476

Solution 1

It is the bitwise shift operator. Specifically, the left-shift operator. It takes the left-hand argument and shifts the binary representation to the left by the number of bits specified by the right-hand argument, for example:

1 << 2 = 4

because 1 (decimal) is 1 (binary); left-shift twice makes it 100 which is 4 in decimal.

1 << 5 = 32

because 100000 in binary is 32 in decimal.

Right shift (>>) does the same thing but to the right.

Solution 2

Easy trick to get result of the left shift operation, e.g.

15 << 2 = 15 * (2*2) = 60

15 << 3 = 15 * (2*2*2) = 120

15 << 5 = 15 * (2*2*2*2*2) = 480

and so on..

So it's:

(number on left) multiplied by (number on right) times 2.

Same goes for right shift operator (>>), where:

(number on left) divided by (number on right) times 2

Solution 3

"<<" is a bit-shift left. Please review PHP's bitwise operators. http://php.net/manual/en/language.operators.bitwise.php

A more in-depth explanation:

This means multiply by two because it works on the binary level. For instance, if you have the number 5 in binary

 0101

and you bit-shift left once to (move each bit over one position)

 1010

then your result is 10. Working with binary (from right to left) is 2^0, 2^1, 2^2, 2^3, and so on. You add the corresponding power of two if you see a 1. So our math for our new result looks like this:

 0 + 2^1 + 0 + 2^3
 0 + 2   + 0 + 8 = 10

Solution 4

It is the binary shifting operator:

http://php.net/manual/en/language.operators.bitwise.php

Solution 5

<< Bitwise left shift. This operation shifts the left-hand operand’s bits to the left by a number of positions equal to the right operand, inserting unset bits in the shifted positions.

>> Bitwise right shift. This operation shifts the left-hand operand’s bits to the right by a number of positions equal to the right operand, inserting unset bits in the shifted positions.

NOTE: It’s also interesting to note that these two provide an easy (and very fast) way of multiply/divide integers by a power of two. For example: 1<<5 will give 32 as a result.......

Share:
27,476

Related videos on Youtube

Petrogad
Author by

Petrogad

Ultimate Frisbee Player Software Developer Avid Technology Enthusiast

Updated on July 09, 2022

Comments

  • Petrogad
    Petrogad almost 2 years

    What does the << Operator mean in php?

    Example:

    $t = 5;
    $foo = 1 << ($t);
    echo($foo); 
    

    echo produces: 32

  • Petrogad
    Petrogad over 13 years
    great description. Thank you!
  • Cameron Skinner
    Cameron Skinner over 13 years
    @Jonah: The example is << 2. Updated answer to clarify.
  • gh darvishani
    gh darvishani almost 5 years
    Can you give me some example for >> ?
  • manishk
    manishk almost 3 years
    For 15 >> 2 = (15/2)/2 = 7/2 = 3 (use floor values if result is in decimals). Similarly 35 >> 3 = (((35/2)/2)/2 = (17/2)/2 = 8/2 = 4.