0

I wrote this function but can't find out what's wrong can someone help me please. It gives the output as 513. I have added the function for both binary and gray please help Me! Thanks :)

function xor_c (a,b){
    return (a==b)?'0':'1';
}

function flip(c){
    return (c=='0') ? '1':'0';
}

function BinaryToGray(binary){
let gray='';
gray+=binary[0];
for(let i=1;i<binary.length;i++){
    gray+=xor_c(binary[i-1],binary[i]);
}
return binary;
}

function GrayToBinary(gray){
let binary='';
binary+=gray[0];
for(let i=1;i<gray.length;i++){
    if(gray[i]=='0')
        binary+=binary[i-1];
    else
        binary+=flip(binary[i-1]);
}
return binary;
}

let binary=(01001).toString();
console.log(BinaryToGray(01001));

2 Answers2

0

function xor_c (a,b){
    return (a==b)?'0':'1';
}

function flip(c){
    return (c=='0') ? '1':'0';
}

function BinaryToGray(binary){
binary = binary.split('');
let gray='';
gray += binary[0];
for(let i=1;i<binary.length;i++){
    gray+=xor_c(binary[i-1],binary[i]);
}
return gray;
}

function GrayToBinary(gray){
let binary='';
binary+=gray[0];
for(let i=1;i<gray.length;i++){
    if(gray[i]=='0')
        binary+=binary[i-1];
    else
        binary+=flip(binary[i-1]);
}
return binary;
}

let binary='0101001';
console.log(BinaryToGray(binary));
Lil Devil
  • 663
  • 5
  • 10
0

A few issues:

  • Your BinaryToGray has a wrong return: it just returns the argument that was given. It should return the result, i.e. return gray;

  • The main code passes a number to that function, while the function expects a string in binary notation. The main code has a trace of making a string (to a variable binary), but toString will produce a string in decimal notation by default. You should pass an argument to toString to get a binary representation: toString(2).

  • I suppose you intended 01001 to be a binary literal, but it really is one in base 10: one thousand and one. You must prepend 0b to it, like 0b01001.

trincot
  • 317,000
  • 35
  • 244
  • 286