Skip to content

Instantly share code, notes, and snippets.

@e000
Created April 7, 2011 03:39
Show Gist options
  • Save e000/906993 to your computer and use it in GitHub Desktop.
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.
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