Skip to content

Instantly share code, notes, and snippets.

@hmmhmmhm
Created October 12, 2021 04:40
Show Gist options
  • Select an option

  • Save hmmhmmhm/840abb2990ad47d7832d036b7d37fe9b to your computer and use it in GitHub Desktop.

Select an option

Save hmmhmmhm/840abb2990ad47d7832d036b7d37fe9b to your computer and use it in GitHub Desktop.
typescript ab2str & str2ab
/**
* 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