PHP格雷码 - 异或错误

时间:2012-06-07 17:53:07

标签: php xor gray-code

我在php中编写了这个函数来执行数字的Gray Code

function c_gray($num){
    $bin=decbin($num);  //binary of the number
    $xor=array();
    $xor[]=reset(str_split($bin)); //Get the first bit of binary and put it as the first element of $xor array
    for($i=0;$i<strlen($bin)-1;$i++){  //for any bit of the binary 
            echo $xor[]=$bin[$i] ^ $bin[$i+1]; //do the xor with the next bit of binary and put the result in array $xor
    }
    $res=implode($xor);  //put hte final code in $res
    return $res;
}

问题在于xor。如果我打印$xor数组,那么我只使用$xor[]=reset(str_split($bin));

放置了第一个元素

我错了?

1 个答案:

答案 0 :(得分:1)

您的字符串元素未隐式转换为整数...尝试:

function c_gray($num){
    $bin   = decbin($num);  //binary of the number
    $xor   = array();
    $xor[] = reset(str_split($bin)); //Get the first bit of binary and put it as the first element of $xor array
    for($i=0;$i < strlen($bin)-1; $i++){  //for any bit of the binary
        $xor[] = (int)$bin[$i] ^ (int)$bin[$i+1]; //do the xor with the next bit of binary and put the result in array $xor
    }
    $res  = implode($xor);  //put hte final code in $res
    return $res;
}