PHP 格雷码 - 异或错误

标签 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[]=reset(str_split($bin));

放置的第一个元素

我错在哪里?

最佳答案

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

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

关于PHP 格雷码 - 异或错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10937148/

相关文章:

php按日期从mysql获取数据

PHP Laravel Gallery 将数组拆分为 3 列

c - 如何在 C 中异或两个字节流?

Prolog 实现和/2、或/2、nand/2、nor/2、xor/2

python - 使用 Python 将灰度图像转换为其原始颜色格式

php ->= 和 <= 不工作的 MYSQL 更新查询

algorithm - 快速检查是否设置了奇数位的方法?

c# - 如何从十进制数中获取格雷码

algorithm - 一种使用位翻转迭代所有 k 位数字的算法

php - 显示来自 MySQL 的卷跳过一个卷