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 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存