Skip to content

Instantly share code, notes, and snippets.

@marcelaraujo
Created March 16, 2015 14:13
Show Gist options
  • Select an option

  • Save marcelaraujo/0de8e9ddc776e8a628b6 to your computer and use it in GitHub Desktop.

Select an option

Save marcelaraujo/0de8e9ddc776e8a628b6 to your computer and use it in GitHub Desktop.
Pack and Unpack javascript strings
var pack = function pack (bytes) {
var str = "";
for(var i = 0; i < bytes.length; i += 2) {
var char = bytes[i] << 8;
if (bytes[i + 1])
char |= bytes[i + 1];
str += String.fromCharCode(char);
}
return str;
};
var unpack = function unpack (str) {
var bytes = [];
for(var i = 0; i < str.length; i++) {
var char = str.charCodeAt(i);
bytes.push(char >>> 8);
bytes.push(char & 0xFF);
}
return bytes;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment