Pete Kang Pete Kang - 4 months ago 21
PHP Question

PHP / bitwise operators left shift

Can someone please explain to me why this equals

32
?

$a = 4 << 2 + 1;
echo $a;


Output:


32


I read the manual and found out that
<<
is a bit shift left, but still don't quite grasp the concept.

Answer

If we divide the problem into steps, it becomes easy to follow. I'll first explain the bitwise part so anybody that reaches this question gets the point. In the end you can see a mention to your problem.


Start:

$v = 4;

First we check how many bits are needed for that value.

echo decbin($v); // 3 bits (100)

Then, we left shift it by two:

echo $v << 2; // the value is now 16. Why?

because if we check the bits:

echo decbin($v << 2); // 5 bits (10000) -> the previous 3 bits + 2 shifted
//                                  /\ check that there are more 2 bits now


But we are getting 32 as result, why is that? Well, because in this case, + comes first. It first evaluates the sum (2+1) and only then shifts. Your code is the same as 4 << (2 + 1).

If we check the steps just like before, but knowing it will sum first, it will actually shit it by 3, making the last value have 6 bits instead.

And if we convert the value that was shifted by 3 (100000), we get 32.

Comments