Algo returning non english characters

Hi,

While trying to solve - https://www.freecodecamp.org/challenges/binary-agents , my code is returning –

䉁쥅촶蜏蚠죪촷촶쥎쳉쥅蚠쥎촶蚡눇

I do not know what has gone wrong - kindly suggest how to remove this error , thanks …


function binaryAgent(str) {
    var test = str.split(" ");
    var res =[];
    for(var i = 0; i < test.length; i++){
      res.push(String.fromCharCode(test[i]));
        
    }
    res=res.join("");
    console.log(res);
    
}

binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");

fromCharCode() expects unicode values. You are passing it binary. The characters you are seeing are the ones corresponding to the values you are passing into fromCharCode().

1 Like

Inside the for loop, test[i] will be a string representing a binary number. You need to convert this binary (base of 2) number into a decimal “denary” (base of 10) number. So for example:

test[0] is the first binary number and is “01000001”

When you convert this to decimal you should get the decimal number 65. Once you have this number, your String.fromCharCode(test[0]) convert to the letter “A”.

The purpose of this challenge is to figure out a way to convert the binary number to decimal. Once you figure that out, the rest of your code is fine.

@camperextraordinaire - thanks , so i googled a bit as for me to develop a function to convert binary to decimal would be very tough , found out abt parseInt my updated code -


function binaryAgent(str) {
    var test = str.split(" ");
    var res =[];
    for(var i = 0; i < test.length; i++){
      res.push(String.fromCharCode(parseInt(test[i],2)));
        
    }
    res=res.join("");
    return res;
    
}

binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");