Skip to content

Instantly share code, notes, and snippets.

@hitman401
Created August 3, 2015 11:59
Show Gist options
  • Save hitman401/b248a0e9fecb7cf28280 to your computer and use it in GitHub Desktop.
Save hitman401/b248a0e9fecb7cf28280 to your computer and use it in GitHub Desktop.
Simple snippet to convert utf8 string to bytes and vice versa
function pack(bytes) {
var chars = [];
for(var i = 0, n = bytes.length; i < n;) {
chars.push(((bytes[i++] & 0xff) << 8) | (bytes[i++] & 0xff));
}
return String.fromCharCode.apply(null, chars);
}
function unpack(str) {
var bytes = [];
for(var i = 0, n = str.length; i < n; i++) {
var char = str.charCodeAt(i);
bytes.push(char >>> 8, char & 0xFF);
}
return bytes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment