I got an assignment to convert a given string into binary and back to a string again.
The first part was easy
function stringToBinary(input) {
var characters = input.split('');
return characters.map(function(char) {
return char.charCodeAt(0).toString(2)
}).join('');
}
alert(stringToBinary('test'))
However I cannot get my head around how to break the resulting string into their bytes. I tried this so far:
function binaryToString(input) {
var bits = input.split('');
var byte = '';
return bits.map(function(bit) {
byte = byte + bit;
if (byte.length == 8) {
var char = byte; // how can I convert this to a character again?
byte = '';
return char;
}
return '';
}).join('');
}
alert(binaryToString('1110100110010111100111110100'));
How can I convert a byte into a character again? And it also feels a bit odd. Is there a better, faster way to collect those bytes
There is a problem with your stringToBinary
function. Converting a character to binary only leaves you with the least amount of bits. So you still need to convert it to an 8-bit string.
The other thing is, that you can just get the first 8 digits from your binary and trim your input as you go, like in the following example.
function stringToBinary(input) {
var characters = input.split('');
return characters.map(function(char) {
const binary = char.charCodeAt(0).toString(2)
const pad = Math.max(8 - binary.length, 0);
// Just to make sure it is 8 bits long.
return '0'.repeat(pad) + binary;
}).join('');
}
function binaryToString(input) {
let bytesLeft = input;
let result = '';
// Check if we have some bytes left
while (bytesLeft.length) {
// Get the first digits
const byte = bytesLeft.substr(0, 8);
bytesLeft = bytesLeft.substr(8);
result += String.fromCharCode(parseInt(byte, 2));
}
return result;
}
const binary = stringToBinary('test');
console.log({
binary,
text: binaryToString(binary),
});