What does >> mean in PHP?

后端 未结 8 1897
天涯浪人
天涯浪人 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.

    0 讨论(0)
  • 2021-02-19 05:46

    >> is the binary right-shift operator.

    Your statement shifts the bits in the numeric value 50 four places to the right. Because all integers are represented in two's complement, this equals 3. An easy way to remember this is that one shift to the right is the same as dividing by 2, and one shift to the left is the same as multiplying by 2.

    0 讨论(0)
  • 2021-02-19 05:52

    It shifts the bits down four places.

    50 in binary is 110010.

    Shifted down four places is 11, which is 3.

    0 讨论(0)
  • 2021-02-19 05:54

    50 in binary is 11 0010, shift right by 4 yields 11 which is equal to 3.

    See PHP documentation and Wikipedia.

    0 讨论(0)
  • 2021-02-19 06:02

    Arithmetic shift right.

    0 讨论(0)
  • 2021-02-19 06:04

    It's called a right shift. 'The bits of the left operand are shifted right by the number of positions of the right operand. The bit positions vacated on the left are filled with the sign bit, and bits shifted out on the right are discarded.'

    Information can be found on it here: http://php.comsci.us/etymology/operator/rightshift.php

    0 讨论(0)
提交回复
热议问题