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 :
Why does the buffer method add the 32 bytes - and how can that be avoided (or corrected) ?
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);
}
Post: @Bergi's answer is correct, I did not even look at the buffer Uint8 was created from.
I was not able to reproduce the behavior you had in chrome console, but you can always resort to using DataView to have fine grained control, something like this:
(beware of the endianness, and I did not test the code below, I might have done mistake in the byte orders)
let test8 = new Uint8Array(400);
test8.forEach((d,i,a) => a[i] = 0xff * Math.random() | 0);
function c8to32(uint8, endian = false){ //big endian by default
var cpBuff = new ArrayBuffer(uint8.length),
view = new DataView(cpBuff);
for (let i = 0,v = void(0); i < uint8.length; i += 4){
if(!endian) { //big
v = uint8[i] << 24
| uint8[i + 1] << 16
| uint8[i + 2] << 8
| uint8[i + 3];
} else { //little
v = uint8[i]
| uint8[i + 1] << 8
| uint8[i + 2] << 16
| uint8[i + 3] << 24;
}
view.setFloat32(
i,
v,
endian
);
}
return cpBuff;
}
document.getElementById("resultbig").textContent = c8to32(test8).byteLength;
document.getElementById("resultlittle").textContent = c8to32(test8, true).byteLength;
<div id="resultbig">test</div>
<div id="resultlittle">test</div>