Today, we are going to become translators. The next bonfire in the series, Binary Agent, will have us write a function that takes in a binary string and turn it into characters that we love and understand.
Here’s an example of such a string:
var myString = '01001001 00100111 01101101 01000010 01100001 01110100 01101101 01100001 01101110 00101110 00101110 00101110'; binaryAgent(myString); //-> I'm Batman...
We are going to use the String.fromCharCode() method. This method takes a unicode character code and returns a character. For example:
String.fromCharCode(67); //-> C String.fromCharCode(120); //-> x
But we do not have decimal character codes do we? We are only getting binary strings. Each character code is represented as binary code, and these are separated by spaces, so in theory, if we split (sounds familiar…) the input array into different binary numbers at each space, we could transform this binary code into decimal numbers and get the letter out of that. Let’s put down some code:
function binaryAgent(binaryString) { var result = [], binaryArray = binaryString.split(' '); // We split at every space and get an array. binaryArray.forEach(function(binaryCode) { // A for loop here will work just as well. // Transform each code and push it to result. }); return result.join(''); // We join and return the result array. }
Now that we know how to go about it, let’s see how to transform a binary string into a decimal number, and then use it in conjunction with String.fromCharCode(). We’ll use parseInt for this task. As you probably know, parseInt will take in a first argument and attempt to transform it into an integet. The second and less known parameter will tell it the base (binary, octal, decimal etc.) for the first argument:
var numOne = '4'; parseInt(numOne) //-> 4 (number) - Will use base 10 by default. var numTwo = '101'; parseInt(numTwo, 2) //-> 5 (number) - We tell parseInt to use base 2 for the input.
Now that we can convert binary to decimal, let’s use fromCharCode!
function binaryAgent(binaryString) { var result = [], binaryArray = binaryString.split(' '); binaryArray.forEach(function(binaryCode) { result.push(String.fromCharCode(parseInt(binaryCode, 2))); }); return result.join(''); }
I nested the whole thing into a single line there, here’s a version that is easier to read:
function binaryAgent(binaryString) { var result = [], binaryArray = binaryString.split(' '); binaryArray.forEach(function(binaryCode) { var decimal = parseInt(binaryCode, 2); var charCode = String.fromCharCode(decimal); result.push(charCode); }); return result.join(''); }
As a bonus, try coming up with a function that does the opposite and transforms plain text into a decimal string. Good luck, and have fun coding!