26

How can I convert Binary code to text using JavaScript? I have already made it convert text to binary but is there a way of doing it the other way around?

Here is my code:

function convertBinary() {
  var output = document.getElementById("outputBinary");
  var input = document.getElementById("inputBinary").value;
  output.value = "";
  for (i = 0; i < input.length; i++) {
    var e = input[i].charCodeAt(0);
    var s = "";
    do {
      var a = e % 2;
      e = (e - a) / 2;
      s = a + s;
    } while (e != 0);
    while (s.length < 8) {
      s = "0" + s;
    }
    output.value += s;
  }
}
<div class="container">
  <span class="main">Binary Converter</span><br>
  <textarea autofocus class="inputBinary" id="inputBinary" onKeyUp="convertBinary()"></textarea>
  <textarea class="outputBinary" id="outputBinary" readonly></textarea>
  <div class="about">Made by <strong>Omar</strong></div>
</div>
j08691
  • 204,283
  • 31
  • 260
  • 272
16.uk
  • 569
  • 3
  • 9
  • 19

23 Answers23

46

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"
BillyD
  • 471
  • 4
  • 3
  • You're using `.map` as if you're using`.forEach`. You can use `const binaryAgent = str => str.split(' ').map(bin => String.fromCharCode(parseInt(bin, 2))).join("");` instead. – Константин Ван Sep 27 '16 at 09:45
  • 4
    Ah, I'm stuck on this free code camp exercise, which I see is where you were working from also :) – Cloud Jan 10 '19 at 12:21
  • note: this might be O(n^2); concatenating strings in a loop is a bad habit... instead you should use the join method, as Jeffrey James demonstrates. – Nitsan BenHanoch Jul 30 '20 at 11:30
31

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).

Community
  • 1
  • 1
cxw
  • 16,685
  • 2
  • 45
  • 81
  • Edited to show. Further recommendation: name your functions "X2Y" instead of "convertX". With a name like "convertBinary", it's not immediately clear whether it's converting to or from binary. Using more descriptive function and variable names will help other people understand your code better and will help you understand it better when you come back to it a month later :) . – cxw Feb 12 '14 at 13:35
9

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

Jeffrey James
  • 225
  • 4
  • 10
8

I ran into the same thing where I wanted to have Binary converted to text and this is what I came up with.

function binaryToWords(str) { 
    if(str.match(/[10]{8}/g)){
        var wordFromBinary = str.match(/([10]{8}|\s+)/g).map(function(fromBinary){
            return String.fromCharCode(parseInt(fromBinary, 2) );
        }).join('');
        return console.log(wordFromBinary);
    }
}

binaryToWords('01000011 01101111 01100110 01100110 01100101 01100101 00100000 01101001 01110011 00100000 01100011 01101111 01101100 01100100 ');
TrojanMorse
  • 642
  • 1
  • 8
  • 16
3

Here is the code I wrote which converts binary to string. The only difference - it is shorter and relies on builtin JS functions.

function binarytoString(str) {
  return str.split(/\s/).map(function (val){
    return String.fromCharCode(parseInt(val, 2));
  }).join("");
}
Nigel
  • 387
  • 4
  • 13
3

My solution for converting binary codes to text. Nothing extra. Most simple version, I think.

function binaryAgent(str) {
  return str.split(" ").map(x => String.fromCharCode(parseInt(x, 2))).join("");
}

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

How about this?

function binaryAgent(str) {
  var splitStr = str.split(" ");
  var newVar = splitStr.map(function(val) {
    return String.fromCharCode(parseInt(val,2).toString(10));
  });
  str = newVar.join("");
  return str;
}

binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"); // should return "Aren't bonfires fun!?"
Sankalp Singha
  • 4,461
  • 5
  • 39
  • 58
2

This should work, and you don't need to give it "pretty" binary.

function binaryToString(binary) {
  return binary.replace(/[01]{8}/g, function(v){ 
    return String.fromCharCode(parseInt(v, 2)); 
  });
}
Matt MacPherson
  • 185
  • 2
  • 10
2

if you are looking for 1 line solution.

function binary(str) {
return str.split(/\s/g).map((x) => x = String.fromCharCode(parseInt(x, 2))).join("");
}
//returns "one line"
binary("01101111 01101110 01100101 00100000 01101100 01101001 01101110 01100101");
Farhan Ullah
  • 58
  • 1
  • 5
2

If you are aware that only binary is being passed, you could use this function that has only 1 simple line:

function binaryAgent(str) {
  return str.split(" ").map(input => String.fromCharCode(parseInt(input,2).toString(10))).join("");

}

// Calling the function
binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
J21 B
  • 31
  • 3
2

Shorter Code

function binaryAgent(str) {
  let array = str.split(" ");
  return array.map(code => String.fromCharCode(parseInt(code, 2))).join("");
}

console.log(binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"));
// should return "Aren't bonfires fun!?"
Hamza Dahmoun
  • 1,204
  • 10
  • 16
1

My solution is a whole lot like map, only I used reduce. Break it up into an array, use reduce to convert the characters and add them to a new Array and join the new Array together.

function binaryAgent(str) {
  var sentence = str.split(" ").reduce(function(x, y){
    x.push(String.fromCharCode(parseInt(y, 2)));
    return x;
  }, []).join('');

  return sentence;
}
John
  • 31
  • 4
1

This is also an operation you can delegation on the String prototype, although rarely recommended to update a global object type.

/** Returns a converted binary string to text */
String.prototype.binaryToText = function() {
  return this
    .match(/.{1,8}/g)
    .join(' ')
    .split(' ')
    .reduce((a, c) => a += String.fromCharCode(parseInt(c, 2)), '');
}

const result = '01110101011100000010000001110110011011110111010001100101'.binaryToText();
console.log(result);
Matt D. Webb
  • 3,216
  • 4
  • 29
  • 51
1

One line (Arrow) function:

let binToStr = (str) => str.split(' ').map((x) => String.fromCharCode(parseInt(x,2))).join('')

//Output: "Are fun!"
console.log(binToStr("01000001 01110010 01100101 00100000 01100110 01110101 01101110 00100001"));
0

Another similar answer if someone looking for this

function binaryAgent(str) {

  var strArray = str.split(" ");
  var text ="";
  for(var i = 0 ; i<strArray.length ; i++){
    var char = parseInt(strArray[i],2).toString(10);
    char = String.fromCharCode(char);
    text += char;
  }
  return text;

}

binaryAgent("01101101 01100101 01110110");
Hadnazzar
  • 1,517
  • 19
  • 21
0

A problem that i found every providen solution was that if the binary string ain't "pretty printed" it won't convert it into a string:

function binaryAgent(str) {
  var binString = '';

  str.split(' ').map(function(bin) {
      binString += String.fromCharCode(parseInt(bin, 2));
  });

  return binString;
}
// This displays "Aren't"
binaryAgent('01000001 01110010 01100101 01101110 00100111 01110100');
//But this not
binaryAgent('010000010111001001100101011011100010011101110100');

A quick solution is to remove all the spaces from the string (if there's any, otherwise the instruction to split doesn't work well) every 8 characters:

function binaryAgent(str) {
  // Removes the spaces from the binary string
  str = str.replace(/\s+/g, '');
  // Pretty (correct) print binary (add a space every 8 characters)
  str = str.match(/.{1,8}/g).join(" ");

  var binString = '';

  str.split(' ').map(function(bin) {
      binString += String.fromCharCode(parseInt(bin, 2));
  });

  return binString;
}

// Both display "Aren't"
binaryAgent('01000001 01110010 01100101 01101110 00100111 01110100');
binaryAgent('010000010111001001100101011011100010011101110100');
Carlos Delgado
  • 2,930
  • 4
  • 23
  • 49
0

For those who prefer .forEach() instead of loops, the following works as well:

    function binaryToHuman(str) {
    // split string into an array so we can loop through it
    var newStr=str.split(" ");
    // declare a new array to later push "translated" values into
    var sArr=[];
    // loop through binary array, translate and push translated values into the new array
    newStr.forEach(function(item){
    sArr.push(String.fromCharCode(parseInt(item,2)));
    })

    // join the array back into a string
    return sArr.join("");
    }

    console.log(binaryToHuman("01001001 00100000 01101100 01101111 01110110 01100101 00100001"));
   // returns:
   // I love!
EgorGo
  • 1
0

My solution just uses a regex to split bytes into an array, loops through each byte, converts binary to ascii and makes it into a string at end

function binaryAgent(str) {

  //Splits into an array
  var re = /\s/;
  var newArr=str.split(re)
  var answerArr =[];

  //Decimal Conversion
  for (let i=0; i<newArr.length; i++){
    answerArr.push(String.fromCharCode(parseInt(newArr[i],2)));
  }

  return answerArr.join('');


}

binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
Vincent Tang
  • 3,758
  • 6
  • 45
  • 63
0

Here's my solution with as much ES6 syntax as possible:

const binaryAgent = str => {
    let code = str.split(" ")
    let s = code.map((d) => parseInt(d,2))
    let res = s.map((d) => String.fromCharCode(d))
    return res.join("")
}

binaryAgent("01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 00100001")

It should return I love FreeCodeCamp!

Eldar
  • 9,781
  • 2
  • 10
  • 35
M Nelson
  • 1
  • 1
0
const whoTookTheCarKey = message => 
  message.toString().split(',')
     .map(message => String.fromCharCode(parseInt(message, 2)))
     .join('')enter code here
  • Welcome to StackOverflow. While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. – Federico Baù Jan 06 '21 at 15:12
0

One-liner solution with ES6 syntax, using split, map and join functions


    function convertBinary(binary){
         return binary.split(" ").map((x) => x = String.fromCharCode(parseInt(x, 2))).join("");
    } 

    console.log(convertBinary("01001000 01100101 01101100 01101100 01101111 00100001"));
    //This will print  Hello!

mk23
  • 1,257
  • 1
  • 12
  • 25
0
  1. Separate the binary numbers into an array with the split method.
  2. Use the map method to iterate over each binary number that is in the array and convert it to its corresponding letter with the fromCharCode method of the String object (You must first convert the binary number to decimal as follows: parseInt (bin, 2) for the fromCharCode method to work properly).
  3. Add the letter returned by the fromCharCode method to the variable that will contain the result.
function convertBinary(str) {
  let result = "";
  str.split(" ").map(bin => {
    result += String.fromCharCode(parseInt(bin, 2))
  })
  return result;
}
OpenVek
  • 1
  • 1
  • 2
-1

This is a minor adjustment to JosephD's "One line (Arrow) function" answer...

When an arrow function has a single parameter, you can omit the parenthesis (). You can omit them in both the arrow function and the .map method like so:

let binToStr = str => str.split(' ').map(x => String.fromCharCode(parseInt(x,2))).join('');
Ivar
  • 6,138
  • 12
  • 49
  • 61
itwazluck
  • 1
  • 1