5

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

MauriceNino
  • 6,214
  • 1
  • 23
  • 60
Subha Jeet Sikdar
  • 446
  • 1
  • 4
  • 15
  • 1
    You may check the solution over here: [Covert binary to text using javascript](https://stackoverflow.com/questions/21354235/converting-binary-to-text-using-javascript/21354328) – Shivani Sonagara Jul 03 '19 at 09:29
  • https://stackoverflow.com/questions/21354235/converting-binary-to-text-using-javascript/21354328 – ellipsis Jul 03 '19 at 09:30

3 Answers3

26

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

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

const outputStr = binary
  // split string into an array of base 2 (binary) UTF-16 chars
  .split(' ')
  // map every binary char to a UTF-16 number of base 10
  // and then get the string representation of that UTF-16 number
  .map(bin => String.fromCharCode(parseInt(bin, 2)))
  // join the array back to a single string
  .join('');

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:

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

const outputStr = String.fromCharCode(
  ...binary.split(' ').map(bin => parseInt(bin, 2))
)

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:

const str = `StackOverflow`;

const outputStr = str.split('') // split in single chars
  .map(c => c.charCodeAt(0) // get the UTF-16 code (10 base)
             .toString(2)) // transform it back to a string (2 base)
  .join(' ') // make single string from array

console.log(outputStr);
MauriceNino
  • 6,214
  • 1
  • 23
  • 60
  • Ok bro got everything but what does the code bin mean which is used in first example – Subha Jeet Sikdar Jul 03 '19 at 11:10
  • @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. – MauriceNino Jul 03 '19 at 11:13
  • Bro what does the sign ` mean? – Subha Jeet Sikdar Jul 04 '19 at 01:55
  • These are called [Template Literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals). Check them out, they are really useful in JavaScript. @SubhaJeetSikdar – MauriceNino Jul 04 '19 at 08:35
  • 1
    NB: if you put Unicode characters through this you'll see binary numbers of up to 16 bits in length. – Alnitak Oct 14 '20 at 11:19
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

=======

Abregre
  • 486
  • 4
  • 11
  • 2
    Please add some explanation for your answer so that audience can understand the working of the code – Not A Bot Oct 14 '20 at 13:26
  • 1
    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). – Alnitak Oct 14 '20 at 13:40
1

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(''));
Godsonaddy
  • 27
  • 3
  • 1
    downvote for using `forEach()` with a `push` instead of `.map` . You've copied the accepted answer, and made it _worse_. – Alnitak Oct 14 '20 at 11:19
  • @Alnitak just an alternative. Makes sense to use map tho – Godsonaddy Oct 14 '20 at 11:21
  • 3
    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. – Alnitak Oct 14 '20 at 11:32