Last active
January 3, 2023 16:37
-
-
Save belohlavek/90771ccccb11100e76d1 to your computer and use it in GitHub Desktop.
ASCII to Binary and Binary to ASCII Utility functions in Javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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('');