Converting between strings and ArrayBuffers

后端 未结 24 1188
慢半拍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:22

    The "native" binary string that atob() returns is a 1-byte-per-character Array.

    So we shouldn't store 2 byte into a character.

    var arrayBufferToString = function(buffer) {
      return String.fromCharCode.apply(null, new Uint8Array(buffer));
    }
    
    var stringToArrayBuffer = function(str) {
      return (new Uint8Array([].map.call(str,function(x){return x.charCodeAt(0)}))).buffer;
    }
    

提交回复
热议问题