2017-04-16 17 views
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 

の結果であるが、動作するはずですように私には論理的なようです。

+2

をこれは、演算子の優先順位の問題です。ビット単位の式はカッコで囲む必要があります。これは、比較の優先度が高いためビット単位の操作の前に行われるためです。 if文では、目的の結果を与える構文は 'if(($ days&0x08)== 0x08)'となります。 http://php.net/manual/en/language.operators.precedence.phpおよびhttp://php.net/manual/en/language.operators.bitwise.phpを参照してください。 – drew010

答えて

関連する問題