What does >> mean in PHP?

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

Consider:

echo 50 >> 4;

Output:

3

Why does it output 3?

8条回答
  •  失恋的感觉
    2021-02-19 06:08

    For your convenience, one of the fastest ways to calculate the outputted value from a bitwise shift is to multiply or divide by 2.

    For example echo 50 >> 4;

    Given that this is a bitwise right, it literally means that the value will be decrease, then we can get the output by divide 50 for 2 and 4 times.

    echo 50 >> 4; // 50/(2*2*2*2) ~ 3.

    Given that (from) 48 -> (to) 63/16(2*2*2*2), the result will be more than 2 and less than 4. Then

    echo 48 >> 4; // 48/(2*2*2*2) ~ 3.

    echo 63 >> 4; // 63/(2*2*2*2) ~ 3.

    However, when bitwise left, the result will be totally different as it multiplies by 2 with n times:

    If echo 50 << 4; // 50*(2*2*2*2) ~ 800

    If echo 51 << 4; // 51*(2*2*2*2) ~ 816

    Live example: https://3v4l.org/1hbJe

提交回复
热议问题