Created
October 12, 2021 04:40
-
-
Save hmmhmmhm/840abb2990ad47d7832d036b7d37fe9b to your computer and use it in GitHub Desktop.
typescript ab2str & str2ab
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
| /** | |
| * Converts an ArrayBuffer to a String. | |
| * | |
| * @param buffer - Buffer to convert. | |
| * @returns String. | |
| */ | |
| export const arrayBufferToString = (buffer: ArrayBuffer) => | |
| String.fromCharCode.apply(null, Array.from(new Uint16Array(buffer))) | |
| /** | |
| * Converts a String to an ArrayBuffer. | |
| * | |
| * @param str - String to convert. | |
| * @returns ArrayBuffer. | |
| */ | |
| export const stringToArrayBuffer = (str: string) => { | |
| 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 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment