Skip to content

Instantly share code, notes, and snippets.

@luanvuhlu
Created May 22, 2018 12:10
Show Gist options
  • Save luanvuhlu/b7a3dd1b6798b071e84a3e9e2ce85a17 to your computer and use it in GitHub Desktop.
Save luanvuhlu/b7a3dd1b6798b071e84a3e9e2ce85a17 to your computer and use it in GitHub Desktop.
convert arraybuffer to string and string to arraybuffer
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
function str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint8Array(buf);
for (var i=0, strLen=str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment