Skip to content

Instantly share code, notes, and snippets.

@belohlavek
Last active January 3, 2023 16:37
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save belohlavek/90771ccccb11100e76d1 to your computer and use it in GitHub Desktop.
Save belohlavek/90771ccccb11100e76d1 to your computer and use it in GitHub Desktop.
ASCII to Binary and Binary to ASCII Utility functions in Javascript.
var Util = {
toBinary: function(input) {
var result = "";
for (var i = 0; i < input.length; i++) {
var bin = input[i].charCodeAt().toString(2);
result += Array(8 - bin.length + 1).join("0") + bin;
}
return result;
},
toAscii: function(input) {
var result = "";
var arr = input.match(/.{1,8}/g);
for (var i = 0; i < arr.length; i++) {
result += String.fromCharCode(parseInt(arr[i], 2).toString(10));
}
return result;
}
}
@t-jay-777
Copy link

I did modified a bit your toAscii() function:
function toAscii(str) { return str.split(' ').map(i => String.fromCharCode(parseInt(i, 2)).toString(10)).join(''); }
in ES6 it looks more nice:
const toAscii= (str) => str.split(' ').map(i => String.fromCharCode(parseInt(i, 2)).toString(10)).join('');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment