Reputation: 4423
What does the << Operator mean in php?
Example:
$t = 5;
$foo = 1 << ($t);
echo($foo);
echo produces: 32
Upvotes: 28
Views: 32390
Reputation: 6823
"<<" 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
Upvotes: 8
Reputation: 5461
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
Upvotes: 14
Reputation: 11
<<
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.......
Upvotes: 1
Reputation: 54306
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.
Upvotes: 58
Reputation: 20189
It is the binary shifting operator:
http://php.net/manual/en/language.operators.bitwise.php
Upvotes: 2