How to get binary string from ArrayBuffer?

前端 未结 4 2086
眼角桃花
眼角桃花 2020-12-08 06:03

What is the way to obtain binary string from ArrayBuffer in JavaScript?

I don\'t want to encode the bytes, just get the binary representation as String.

Tha

4条回答
  •  囚心锁ツ
    2020-12-08 06:38

    This has been made much simpler by additions to JavaScript in recent years – here's a one-line method to convert a Uint8Array into a binary-encoded string:

    const toBinString = (bytes) =>
      bytes.reduce((str, byte) => str + byte.toString(2).padStart(8, '0'), '');
    

    Example:

    console.log(toBinString(Uint8Array.from([42, 100, 255, 0])))
    // => '00101010011001001111111100000000'
    

    If you're starting with an ArrayBuffer, create a Uint8Array "view" of the buffer to pass into this method:

    const view = new Uint8Array(myArrayBuffer);
    console.log(toBinString(view));
    

    Source: the Libauth library (binToBinString method)

提交回复
热议问题