Created
April 7, 2011 03:39
-
-
Save e000/906993 to your computer and use it in GitHub Desktop.
so many shitty str -> binary converters out there. here's a decent one.
This file contains hidden or 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
strToBin = (function() { | |
var binarr = [] // build an array to hold the binary form of 0-255 | |
for(var i = 0; i < 256; i++) { | |
bins = '' | |
for(var j = 7; j >= 0; j--) { | |
c = Math.pow(2, j) | |
bins += (i & c) == c ? '1' : '0' | |
} | |
binarr.push(bins) | |
} | |
return function(str, sep) { // return anonymous function using local closure. | |
sep = sep || '' | |
out = [] | |
c = str.charCodeAt | |
l = str.length | |
for(var i = 0; i < l; i++) { | |
out.push(binarr[c(i) & 255]) // prevent overflow. | |
} | |
return out.join(sep); | |
} | |
}()) | |
console.log(strToBin) | |
console.log(strToBin('hello world', ' ')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment