Skip to content

Instantly share code, notes, and snippets.

@socheatsok78
Created April 5, 2024 06:09
Show Gist options
  • Save socheatsok78/6f7c02d11eba18a5c2ec7c4f7582ca4d to your computer and use it in GitHub Desktop.
Save socheatsok78/6f7c02d11eba18a5c2ec7c4f7582ca4d to your computer and use it in GitHub Desktop.
A browser implementation for String <-> ArrayBuffer
/*
Convert an ArrayBuffer into a string
from https://developer.chrome.com/blog/how-to-convert-arraybuffer-to-and-from-string/
*/
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
/*
Convert a string into an ArrayBuffer
from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String
*/
function str2ab(str) {
const buf = new ArrayBuffer(str.length);
const bufView = new Uint8Array(buf);
for (let 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