Inder Inder - 3 months ago 21
Javascript Question

ASCII to binary function

How to reverse this function? It creates a 80-bit binary code from the text, I found it on the internet but do not know how to reverse the operation and make the resulting binary code to restore the text.

var ascii2bin = function(ascii)
{
var bin = "00000000000000000000000000000000000000000000000000000000000000000000000000000000";
for (var i = 0; i < ascii.length; i++)
{
var code = ascii.charCodeAt(i);
bin += ('00000000' + code.toString(2)).slice(-8);
}
return bin.slice(-10 * 8).split('').reverse();
}

Answer

Your function truncates the result to ten characters worth of information (see the -10 in the last line), so only inputs of less than that length can be reversed:

var bin2ascii = function(bin) {
    return bin.reverse().join('').match(/.{8}/g).map(
      x => String.fromCharCode(parseInt(x, 2))
    ).join('');
}

Tests:

bin2ascii( ascii2bin( '' ) ); // ''
bin2ascii( ascii2bin( 'foo bar' ) ); // 'foo bar'
bin2ascii( ascii2bin( 'Test 123' ) ); // 'Test 123'
bin2ascii( ascii2bin( 'This is a long string' ) ); // 'ong string'
Comments