2

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.

7
  • Is this homework? It should be easy to look up. Commented Feb 27, 2011 at 4:35
  • Homework? What have you tried so far? Commented Feb 27, 2011 at 4:36
  • @sunmoon: If your answer gives the algorithm, what do you need help with? Commented Feb 27, 2011 at 4:41
  • I am looking if there is any other approach to solve this. Commented Feb 27, 2011 at 4:46
  • @sunmoon, if the input strings are short enough, there's always lookup tables. :) Commented Feb 27, 2011 at 5:00

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

if this is the answer to your own question then mark it as answer :)
Warning - this answer is slightly incorrect. The correct formula for Bn-1 is Bn-1 = Bn XOR Gn-1. See here for more info.
0

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/

Comments

0
<?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));

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.