Skip to content

Instantly share code, notes, and snippets.

@AndrewLeedham
Created October 1, 2019 16:50
Show Gist options
  • Save AndrewLeedham/a7f41ac6bb678f1eb21baf523aa71fd5 to your computer and use it in GitHub Desktop.
Save AndrewLeedham/a7f41ac6bb678f1eb21baf523aa71fd5 to your computer and use it in GitHub Desktop.
/**
* Converts an ArrayBuffer to a String.
*
* @param buffer - Buffer to convert.
* @returns String.
*/
export default function arrayBufferToString(buffer: ArrayBuffer): string {
return String.fromCharCode.apply(null, Array.from(new Uint16Array(buffer)));
}
/**
* Converts a String to an ArrayBuffer.
*
* @param str - String to convert.
* @returns ArrayBuffer.
*/
export default function stringToArrayBuffer(str: string): ArrayBuffer {
const stringLength = str.length;
const buffer = new ArrayBuffer(stringLength * 2);
const bufferView = new Uint16Array(buffer);
for (let i = 0; i < stringLength; i++) {
bufferView[i] = str.charCodeAt(i);
}
return buffer;
}
@Incedo0808
Copy link

export default function arrayBufferToString(buffer: ArrayBuffer): string {
return String.fromCharCode.apply(null, Array.from(new Uint16Array(buffer)));
}

works for me but when I loop through array of buffers then getting "Maximum call stack size exceeded" error.

e.g
const buffers = [buffer1, buffer2, buffer 3...buffer-n]
const bufStrings = buffers.map(arrayBufferToString); ------error line is this.

Please help

@AndrewLeedham
Copy link
Author

This is just a TS conversion, might be better asking for implementation help in the original gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment