Skip to content

Instantly share code, notes, and snippets.

@paschalidi
Forked from skratchdot/arrayBufferToString.js
Created January 24, 2019 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paschalidi/ff366c84bb9befe905474c1f4ccb4ce1 to your computer and use it in GitHub Desktop.
Save paschalidi/ff366c84bb9befe905474c1f4ccb4ce1 to your computer and use it in GitHub Desktop.
Array Buffer -> String and String -> ArrayBuffer conversions in javascript
// source: http://stackoverflow.com/a/11058858
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
// source: http://stackoverflow.com/a/11058858
function str2ab(str) {
var buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
var bufView = new Uint16Array(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