【问题标题】:PHP Gray Code - XOR errorPHP 格雷码 - XOR 错误
【发布时间】:2012-06-07 17:53:07
【问题描述】:

我在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[]=reset(str_split($bin)); 的第一个元素

我哪里错了?

【问题讨论】:

    标签: php xor gray-code


    【解决方案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;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-16
      • 2017-06-07
      • 2017-01-12
      • 2015-02-28
      • 2015-10-19
      • 2010-12-14
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      相关资源
      最近更新 更多