'Binary to String in JavaScript

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



Solution 1:[1]

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 2:[2]

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(''));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Godsonaddy