Converting Binary to text using JavaScript

I recently completed an exercise on this using a for loop. Hope it's useful:

function binaryAgent(str) {

var newBin = str.split(" ");
var binCode = [];

for (i = 0; i < newBin.length; i++) {
    binCode.push(String.fromCharCode(parseInt(newBin[i], 2)));
  }
return binCode.join("");
}
binaryAgent('01000001 01110010 01100101 01101110 00100111 01110100');
//translates to "Aren't"

EDIT: after learning more JavaScript, I was able to shortened the solution:

function binaryAgent(str) {

var binString = '';

str.split(' ').map(function(bin) {
    binString += String.fromCharCode(parseInt(bin, 2));
  });
return binString;
}
binaryAgent('01000001 01110010 01100101 01101110 00100111 01110100');
//translates to "Aren't"

Use toString(2) to convert to a binary string. For example:

var input = document.getElementById("inputDecimal").value;
document.getElementById("outputBinary").value = parseInt(input).toString(2);

or parseInt(input,10) if you know the input should be decimal. Otherwise input of "0x42" will be parsed as hex rather than decimal.

EDIT: Just re-read the question. To go from binary to text, use parseInt(input,2).toString(10).

Everything above is for numbers only. E.g., 4 <-> 0100. If you want 4 <-> decimal 52 (its ASCII value), use String.fromCharCode() (see this answer).

EDIT 2: per request for where everything fits, try this:

function BinToText() {
    var input = document.getElementById("inputBinary").value;
    document.getElementById("outputText").value = parseInt(input,2).toString(10);
}
...
<textarea autofocus class="inputBinary" id="inputBinary" onKeyUp="BinToText()"></textarea>
<textarea class="outputBinary" id="outputText" readonly></textarea>

If you put 0100 in inputBinary, you should get 4 in outputText (not tested).


Similar to another answer if someone is still looking for this. the first split returns an list of strings, each of which represents a binary character.

Then we call map on each of these strings eg, "11001111" or whatever and return the fromCharCode on that element with parseInt nested. Then put .join() on the total returned value and it should work.

function binaryAgent3(str) {

  return str.split(" ").map(function(elem) {
    return String.fromCharCode(parseInt(elem, 2));
  }).join("")

}

Original problem: http://www.freecodecamp.com/challenges/binary-agents