What does >> mean in PHP?

后端 未结 8 1895
天涯浪人
天涯浪人 2021-02-19 05:13

Consider:

echo 50 >> 4;

Output:

3

Why does it output 3?

8条回答
  •  青春惊慌失措
    2021-02-19 05:44

    As documented on php.org, the >> operator is a bitwise shift operator which shifts bits to the right:

    $a >> $b - Shift the bits of $a $b steps to the right (each step means "divide by two")

    50 in binary is 110010, and the >> operator shifts those bits over 4 places in your example code. Although this happens in a single operation, you could think of it in multiple steps like this:

    • Step 1 - 00011001
    • Step 2 - 00001100
    • Step 3 - 00000110
    • Step 4 - 00000011

    Since binary 11 is equal to 3 in decimal, the code outputs 3.

提交回复
热议问题