Created
March 3, 2016 04:43
-
-
Save skratchdot/e095036fad80597f1c1a to your computer and use it in GitHub Desktop.
Array Buffer -> String and String -> ArrayBuffer conversions in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// source: http://stackoverflow.com/a/11058858 | |
function ab2str(buf) { | |
return String.fromCharCode.apply(null, new Uint16Array(buf)); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
const byteArrayStringA = String.fromCharCode.apply(null, Array.from(new Uint8Array(anArrayBufferA)));
const byteArrayString = String.fromCharCode.apply(null, Array.from(new Uint8Array(anArrayBufferB)));
const byteArrayString = String.fromCharCode.apply(null, Array.from(new Uint8Array(anArrayBufferC)));
The above code giving me "Maximum call stack size exceeded" error.
Please help
I am getting this error when i execute above code:
multipart.ts:33:30 - error TS2339: Property 'charCodeAt' does not exist on type 'any[]'.
33 bufView[i] = post_data.charCodeAt(i);
~~~~~~~~~~
Try using:
function str2ab(text) {
return new TextEncoder().encode(text);
}
@erycson - nice! It looks like TextEncoder/TextDecoder is now a global in node (as of v11.0.0). It was added in the util
lib in v8.3.0.
Following your example. the ab2str
function can be rewritten:
function ab2str(buf) {
return new TextDecoder().decode(buf);
}
Very good! Had to change the Uint16Array to Uint8Array and worked like a charm!
Thanks! worked
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I just posted a TS conversion of this: https://gist.github.com/AndrewLeedham/a7f41ac6bb678f1eb21baf523aa71fd5 feel free to use it. I used
Array.from
to convert theUint16Array
to anumber[]
. Casting will also work if you don't want the extra operation.