Search code examples
javascriptarraybuffer

Converting from a Uint8Array to an ArrayBuffer prepends 32 bytes?


Consider the input bytes that is a 400byte Uint8Array. The following code converts it first to an ArrayBuffer via the .buffer method and subsequently to a Float32Array :

  static bytesToFloatArray(bytes) {
      let buffer = bytes.buffer; // Get the ArrayBuffer from the Uint8Array.
      let floats = new Float32Array(buffer);
      return floats
  }

The surprise is that the conversion to the ArrayBuffer prepends 32 bytes - which is reflected in having 8 extra "0" float values at the beginning of the subsequent Float32Array :

enter image description here

Why does the buffer method add the 32 bytes - and how can that be avoided (or corrected) ?


Solution

  • Why does the buffer method add the 32 bytes?

    It didn't. The buffer had 432 bytes in the first place, even before the Uint8Array was created on it. The difference comes from the typed array using an offset and/or a length which essentially restrict the view to a slice of the buffer.

    And how can that be avoided (or corrected)?

    Use the same offset and adjusted length:

    function bytesToFloatArray(bytes) {
       return new Float32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength/Float32Array.BYTES_PER_ELEMENT);
    }