Converting between strings and ArrayBuffers

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

    In case you have binary data in a string (obtained from nodejs + readFile(..., 'binary'), or cypress + cy.fixture(..., 'binary'), etc), you can't use TextEncoder. It supports only utf8. Bytes with values >= 128 are each turned into 2 bytes.

    ES2015:

    a = Uint8Array.from(s, x => x.charCodeAt(0))
    

    Uint8Array(33) [2, 134, 140, 186, 82, 70, 108, 182, 233, 40, 143, 247, 29, 76, 245, 206, 29, 87, 48, 160, 78, 225, 242, 56, 236, 201, 80, 80, 152, 118, 92, 144, 48

    s = String.fromCharCode.apply(null, a)
    

    "ºRFl¶é(÷LõÎW0 Náò8ìÉPPv\0"

提交回复
热议问题