php synatax $b = (6 << 1); clarification

82 views Asked by At

I am not clearly understand about the following code snippets.

$a = (5 << 0);
$b = (6 << 1);
echo $a|$b;

From php.net i knew that << operator use for shift left but not clear how it works and what is the uses of | operator. Any explanation is highly appreciated. Thank you

4

There are 4 answers

0
Sami Kuhmonen On

5 << 0 produces just 5, since no shift is done. 6 << 1 will shift the bits in 6 (110b) one to the left, which will produce 12 (1100b). So it is multiplying by two essentially.

The | operator is bitwise or, which operates on the bits of 5 (0101b) and 12 (1100b) producing 13 (1101b)

0
user1718074 On

6 is '110' in binary. If you shift '110' once to the left you get '1100' which is 12

0
user3476093 On

<< is the bitwise shift left operator:

00000110 is 6 in binary

6 << 1 means that each bit will be shifted 1 to the left:

00000110 (6)

becomes

00001100 (12)

so... 6 << 1 = 12

5 << 0 makes no difference as none of the bits are being shifted (5 << 0 = 5).


| is the bitwise 'or' operator:

5|12 makes:

00000101 | 00001100

This operator means if both bits are 0, the result will be 0, otherwise 1:

00000101 (5)

00001100 (12)

00001101 (13)

So 5|12 = 13

0
Ye Min Htut On

Hope you can find the solution here

Strange print behaviour in PHP?

for more information, you can check this link

Reference - What does this symbol mean in PHP?