PHP 按位运算未返回正确值

PHP bitwise operations not returning correct values

我有一个函数,它接受一个数字和 returns 一个对应于天数的数组(该数字将针对一周中的每一天进行位屏蔽)。但是,该数组为某些值返回所有日期,为其他值返回一个空数组。 下面是函数

function get_days($days) {
    $days_arr = array();


echo "days: " . decbin($days) . " - type: " . gettype($days) . "<br/>";
echo "type1: " . gettype($days & 0x01) . " - type2: " . gettype(0x01) . "<br/>";
echo "days & 0x01 = " . dechex($days & 0x01) . " = " . ($days & 0x01 == 0x01) . "<br/>";
echo "days & 0x02 = " . dechex($days & 0x02) . " = " . ($days & 0x02 == 0x02) . "<br/>";
echo "days & 0x04 = " . dechex($days & 0x04) . " = " . ($days & 0x04 == 0x04) . "<br/>";
echo "days & 0x08 = " . dechex($days & 0x08) . " = " . ($days & 0x08 == 0x08) . "<br/>";
echo "days & 0x10 = " . dechex($days & 0x10) . " = " . ($days & 0x10 == 0x10) . "<br/>";


    if($days & 0x01 == 0x01)
        $days_arr[] = 'M';

    if($days & 0x02 == 0x02)
        $days_arr[] = 'T';

    if($days & 0x04 == 0x04)
        $days_arr[] = 'W';

    if($days & 0x08 == 0x08)
        $days_arr[] = 'H';

    if($days & 0x10 == 0x10)
        $days_arr[] = 'F';

    return $days_arr;
}

下面是回显的结果

days: 10101 - type: integer
type1: integer - type2: integer
days & 0x01 = 1 = 1
days & 0x02 = 0 = 1
days & 0x04 = 4 = 1
days & 0x08 = 0 = 1
days & 0x10 = 10 = 1
days: 1010 - type: integer
type1: integer - type2: integer
days & 0x01 = 0 = 0
days & 0x02 = 2 = 0
days & 0x04 = 0 = 0
days & 0x08 = 8 = 0
days & 0x10 = 0 = 0

我似乎无法弄清楚问题背后的原因,在我看来这应该有效。

这是运算符优先级问题。参见:

http://php.net/manual/en/language.operators.precedence.php

所以 == 高于 &。你不应该这样做:

$days & 0x02 == 0x02

但是:

($days & 0x02) == 0x02