Converting between strings and ArrayBuffers

后端 未结 24 909
慢半拍i
慢半拍i 2020-11-22 04:50

Is there a commonly accepted technique for efficiently converting JavaScript strings to ArrayBuffers and vice-versa? Specifically, I\'d like to be able to write the contents

24条回答
  •  遥遥无期
    2020-11-22 05:27

    The following is a working Typescript implementation:

    bufferToString(buffer: ArrayBuffer): string {
        return String.fromCharCode.apply(null, Array.from(new Uint16Array(buffer)));
    }
    
    stringToBuffer(value: string): ArrayBuffer {
        let buffer = new ArrayBuffer(value.length * 2); // 2 bytes per char
        let view = new Uint16Array(buffer);
        for (let i = 0, length = value.length; i < length; i++) {
            view[i] = value.charCodeAt(i);
        }
        return buffer;
    }
    

    I've used this for numerous operations while working with crypto.subtle.

提交回复
热议问题