格雷码到二进制的转换

发布于 2024-10-19 13:12:09 字数 222 浏览 9 评论 0原文

给定一个数字的格雷码,找到该数字的二进制代码。

格雷码是一种二进制数字系统,其中两个连续值仅相差一位。

例如两位格雷码是: 0 - 00 1 - 01 2 - 11 3 - 10

二进制为:

0 - 00 1 - 01 2 - 10 3 - 11

提供一种将数字的格雷码转换为二进制码的算法。

例如,输入为 11。预期输出为 10。

Given a gray code for a number, find the binary code for the number.

Gray code is a binary numeral system where two successive values differ in only one bit.

For Example two bit gray code is:
0 - 00
1 - 01
2 - 11
3 - 10

Binary is:

0 - 00
1 - 01
2 - 10
3 - 11

Provide an algorithm to convert the gray code of the number to binary code.

For example, input is 11. Expected output is 10.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

尸血腥色 2024-10-26 13:12:09

将格雷码转换为二进制的方法是:

保留最高有效位,其余位继续对连续位进行异或。

即 Gn Gn-1 Gn-2 ........ G1 为格雷码,Bn Bn-1 .......B1 为二进制码。

Bn= Gn 并且对于所有其他位 Bn-1 = Gn-1 XOR Gn

Converting the Gray code to binary is:

Retain the Most significant bit as it is and for the rest of the bits keep xoring the successive bits.

ie Gn Gn-1 Gn-2 ........ G1 is the gray code and Bn Bn-1 .......B1 is the binary code.

Bn= Gn and for all the other bits Bn-1 = Gn-1 XOR Gn

公布 2024-10-26 13:12:09

如果您想要一种简单的方法,可以使用一个很好的在线格雷码转换器:http: //www.convertforfree.com/gray-code-converter/

If you want an easy way there is a good online gray code converter that you can use: http://www.convertforfree.com/gray-code-converter/

飘落散花 2024-10-26 13:12:09
<?php

函数 gry_code($n) {

if($n == 0 || $n > 65 ) {

    return "Invalid input please input between 1 to 65";
    exit;

} 

$arr = array();

array_push($arr,"0","1");

$i = 0;
$j = 0;

 for ($i = 2; $i < (1<<$n); $i = $i<<1)
 {
    //duplicate the arr contents in reverse order
    for ($j = $i-1 ; $j >= 0 ; $j--)

    array_push($arr,$arr[$j]);

    // append 0 to the first half
    for ($j = 0 ; $j < $i ; $j++)
        $arr[$j] = "0".$arr[$j];

    // append 1 to the second half
    for ($j = $i ; $j < 2*$i ; $j++)
        $arr[$j] = "1".$arr[$j];
}
//return $arr;
$arr = array_slice($arr, -$n);
foreach($arr as $key => $arrx) {

    echo $arrx."\n";


}

//return $arr;

}

print_r(gry_code(5));

?>

<?php

function gry_code($n) {

if($n == 0 || $n > 65 ) {

    return "Invalid input please input between 1 to 65";
    exit;

} 

$arr = array();

array_push($arr,"0","1");

$i = 0;
$j = 0;

 for ($i = 2; $i < (1<<$n); $i = $i<<1)
 {
    //duplicate the arr contents in reverse order
    for ($j = $i-1 ; $j >= 0 ; $j--)

    array_push($arr,$arr[$j]);

    // append 0 to the first half
    for ($j = 0 ; $j < $i ; $j++)
        $arr[$j] = "0".$arr[$j];

    // append 1 to the second half
    for ($j = $i ; $j < 2*$i ; $j++)
        $arr[$j] = "1".$arr[$j];
}
//return $arr;
$arr = array_slice($arr, -$n);
foreach($arr as $key => $arrx) {

    echo $arrx."\n";


}

//return $arr;

}

print_r(gry_code(5));

?>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文