Binary String to Text

Ever wanted to know how to write something in binary?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function textToBinaryString(text) {
let binaryArray = [];
for (let i = 0; i < text.length; i++) {
// string.charCodeAt(index) will give you the UTF-16 code point of a character at a given index
let charCode = text.charCodeAt(i);
// Number.toString(radix) takes a number and returns the string equivalent of that number in the provided base (radix)
let binary = charCode.toString(2);
// Since we know that we're going to be working with just letters a-zA-Z, we know we only care about up to 8 bits of data, so we can pad the start of the string so that a binary letter is represented by 8 bits
let binaryString = binary.padStart(8, 0);
binaryArray.push(binaryString);
}
// Now in order to get a string rather than the array, we need to join the elements of the array together. Since we want to differentiate our letters so they are more easily readable, we can include spaces between each letter.
return binaryArray.join(" ");
}

Ever wanted to convert a binary string to text?

Let’s say we have the binary string “01010100 01001000 01000001 01001110 01001011 00100000 01011001 01001111 01010101” :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function binaryStringToText(binaryString) {
let binaryLetters = binaryString.split(" "); // Each letter is represented by an 8-bit binary string

let sentenceAsArray = binaryLetters.map(binaryLetter => {
// Each letter is first parsed as an integer using the radix (number base) of 2 (for binary) in order to get the character code for that letter
let charCode = parseInt(binaryLetter, 2);
/* If you were to have a separate function just handling this conversion to character codes, you would get an array like:
[84, 72, 65, 78, 75, 32, 89, 79, 85]
*/

// We then get the letter by calling the String method fromCharCode to get the ASCII value associated with that char code

/* Since we're only dealing with 8-byte strings, it's backward-compatable with with ASCII, so you could look the values up in an ASCII table:
84 - T
72 - H
65 - A
78 - N
75 - K
32 - Space
89 - Y
79 - O
85 - U
*/
let letter = String.fromCharCode(charCode);
return letter;
});

/* The above map returns an array like this:
['T', 'H', 'A', 'N', 'K', ' ', 'Y', 'O', 'U']
So in order to get the sentence back in string form, you just join the elements of the array on an empty string
*/

let sentence = sentenceAsArray.join("");
return sentence;
// "THANK YOU"
}