-1

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.

FirstOne
  • 6,033
  • 7
  • 26
  • 45
Etep
  • 2,721
  • 4
  • 17
  • 28
  • See: http://stackoverflow.com/q/3737139/3933332 and http://php.net/manual/en/language.operators.precedence.php – Rizier123 Jul 31 '16 at 20:38
  • 1
    That's the same as `( 4 << (2 + 1) )`: [https://eval.in/614829](https://eval.in/614829). – FirstOne Jul 31 '16 at 20:40
  • [Cross-posting](https://www.reddit.com/r/PHP/comments/4viwf5/php_bitwise_operators_left_shift/) looks very unappreciative of other peoples´ time. – mario Aug 01 '16 at 00:23

1 Answers1

3

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.

FirstOne
  • 6,033
  • 7
  • 26
  • 45