Binary to original string conversion in JavaScript


We are required to write a JavaScript function that takes in a string that represents a binary code. The function should return the alphabetical representation of the string.

For example −

If the binary input string is −

const str = '1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100';

Then the output should be −

const output = 'Hello World';

Example

The code for this will be −

const str = '1001000 1100101 1101100 1101100 1101111 100000 1010111
1101111 1110010 1101100 1100100';
const binaryToString = (binary = '') => {
   let strArr = binary.split(' ');
   const str = strArr.map(part => {
      return String.fromCharCode(parseInt(part, 2));
   }).join('');
   return str;
};
console.log(binaryToString(str));

Output

And the output in the console will be −

Hello World

Updated on: 23-Nov-2020

261 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements