-
-
Save skratchdot/e095036fad80597f1c1a to your computer and use it in GitHub Desktop.
// 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; | |
} |
Good, but typescript complains that new Uint16Array(buf)
cannot be converted to number[]
.
Good, but typescript complains that
new Uint16Array(buf)
cannot be converted tonumber[]
.
Use this code to convert an array buffer to a number
convertArrayBufferToNumber(buffer: ArrayBuffer){
const bytes = new Uint8Array(buffer);
const dv = new DataView(bytes.buffer);
return dv.getUint16(0, true);
}
Very good! Had to change the Uint16Array to Uint8Array and worked like a charm!
Use this code to convert an array buffer to a number
You can cast the Uint8Array (or any other ArrayBufferView) to number[] - it's working fine in my case -
Why does it need to be Uint16Array ? What 's the cost of instantiating another ArrayBufferView ? is it minimal right ? I my case I work both with binary and text files and I read both using Uint8Array and this method works fine just passing it directly and in TypeScript I must cast to any:
const s = String.fromCharCode.apply(null, anArrayBufferView as any)
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 the Uint16Array
to a number[]
. Casting will also work if you don't want the extra operation.
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
good!