duanci1858 2012-06-07 17:53
浏览 132
已采纳

PHP格雷码 - 异或错误

I wrote this function in php to do the Gray Code of a number:

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;
}

The problem is with the xor. if I print $xor array there is just the first element that i put with $xor[]=reset(str_split($bin));

Where I mistake?

  • 写回答

1条回答 默认 最新

  • douxiuyu2028 2012-06-07 18:10
    关注

    Your string elements are not implicitly converted to ints ... try:

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python