Binary to String in JavaScript

14,326

Solution 1

Use String.fromCharCode() and parseInt( , 2) like this:

let binary = `1010011 1110100 1100001 1100011 1101011 
1001111 1110110 1100101 1110010 1100110 
1101100 1101111 1110111`;

let outputStr = binary.split(' ') //Split string in array of binary chars
   .map(bin => String.fromCharCode(parseInt(bin, 2))) //Map every binary char to real char
   .join(''); //Join the array back to a string

console.log(outputStr);
  • String.fromCharCode(number) will return a String from a UTF-16 char code
  • parseInt(binary , 2) will transform a base 2 number string into a base 10 number

Edit:

As the String.fromCharCode() function accepts multiple chars as parameters, you could also use the spread operator like so:

let binary = `1010011 1110100 1100001 1100011 1101011 
1001111 1110110 1100101 1110010 1100110 
1101100 1101111 1110111`;

let outputStr = String.fromCharCode(
  ...binary.split(' ') //Split string in array of binary chars
       .map(bin => parseInt(bin, 2)) //Map every base 2 'number' to base 10
)

console.log(outputStr);

Edit 2:

As this answer gets more traffic over time, I am going to also add the solution to do it the other way around too ... just in case:

let binary = `StackOverflow`;

let outputStr = binary.split('') // split in single chars
                      .map(c => c.charCodeAt(0) // get the charcode (10 base)
                                  .toString(2)) // transform it back to a string (2 base)
                      .join(' ') // make single string from array

console.log(outputStr);

Note:

The ... operator is the so called Spread Operator which transforms an array into a number of parameters.

Example:

//A function that takes an array (of strings) as an argument
func(['string 1', 'string 2'])
//A function that takes a list of strings as an argument
func2(...['string 1', 'string 2'])
//will internally be translated to:
func2('string 1', 'string 2')

Solution 2

str ="01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"
    
    
function binaryAgent(str) {
      return str.split(' ').map(letter=>String.fromCharCode(parseInt(letter, 2))).join('')
     
}
    
console.log(binaryAgent(str))
  • First we use the .split() method to convert the string to array using the ' '(space character)

  • After that we use the .map() high-order loop method to iterate through each binary-code-letter

  • For each binary-code-letter we use String.fromCharCode() on parseInt('each letter',2)=> which converts the binary string to a number. The second argument "2" of the parseInt method which is called(radix) is to define which numeral system we want to use.

  • Finally we can join the manipulated array back together calling the join('') method but this time we don't use a space between

=======

Solution 3

const binary = `1010011 1110100 1100001 1100011 1101011 
1001111 1110110 1100101 1110010 1100110 
1101100 1101111 1110111`;

const inputStr = binary.split(' ');
const output = [];
inputStr.forEach(item => {output.push(String.fromCharCode(parseInt(item, 2)))});
console.log(output.join(''));
Share:
14,326
Subha Jeet Sikdar
Author by

Subha Jeet Sikdar

Just a student

Updated on June 09, 2022

Comments

  • Subha Jeet Sikdar
    Subha Jeet Sikdar almost 2 years

    I have created a JavaScript program to convert a string into binary.

    Input: StackOverflow
    Output: 1010011 1110100 1100001 1100011 1101011 
    1001111 1110110 1100101 1110010 1100110 
    1101100 1101111 1110111 
    

    Now I want to convert that binary back into a string like below. Is there any possible way of doing this?

    Input: 1010011 1110100 1100001 1100011 1101011 
    1001111 1110110 1100101 1110010 1100110 
    1101100 1101111 1110111 
    
    Output StackOverflow
    

    Thanks

  • Subha Jeet Sikdar
    Subha Jeet Sikdar almost 5 years
    Ok bro got everything but what does the code bin mean which is used in first example
  • MauriceNino
    MauriceNino almost 5 years
    @SubhaJeetSikdar bin is the name of the parameter for the function you pass to map. The function map takes an arrow function with one parameter which you can give any name you like. bin could essentially be called someVariable too. The variable itself represents one element from the array. The map function iterates over all elements of the array and applies the arrow function (varName => parseInt(varName , 2)) on each.
  • Subha Jeet Sikdar
    Subha Jeet Sikdar almost 5 years
    Bro what does the sign ` mean?
  • MauriceNino
    MauriceNino almost 5 years
    These are called Template Literals. Check them out, they are really useful in JavaScript. @SubhaJeetSikdar
  • Alnitak
    Alnitak over 3 years
    NB: if you put Unicode characters through this you'll see binary numbers of up to 16 bits in length.
  • Alnitak
    Alnitak over 3 years
    downvote for using forEach() with a push instead of .map . You've copied the accepted answer, and made it worse.
  • Admin
    Admin over 3 years
    @Alnitak just an alternative. Makes sense to use map tho
  • Alnitak
    Alnitak over 3 years
    using foreach/push instead of map is an anti-pattern. There is no good reason for it, and it would be a down-mark in any code review.
  • Not A Bot
    Not A Bot over 3 years
    Please add some explanation for your answer so that audience can understand the working of the code
  • Alnitak
    Alnitak over 3 years
    and also explain how it improves on the accepted answer (hint: it doesn't, because apart from wrapping into a function the code is identical apart from the variable names).