2
我有一個函數,它接受一個數字並返回與天數對應的數組(該數字將在一週中的每一天被屏蔽)。但是,數組將返回特定值的所有日期,併爲另一個值返回一個空數組。 下面是功能PHP按位操作不返回正確的值
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
我似乎無法弄清楚這個問題背後的原因的結果,這似乎是合乎邏輯,我認爲這應該工作。
這是一個運算符優先級的問題。按位表達式應加括號,因爲比較具有更高的優先級,所以它發生在按位操作之前。在if語句中,給出所需結果的語法是'if(($ days&0x08)== 0x08)'。見http://php.net/manual/en/language.operators.precedence.php和http://php.net/manual/en/language.operators.bitwise.php – drew010