I would suggest using Buffer.readFloatLE and / or Buffer.readFloatBE to read the required float32 numbers from the buffer.
The example below writes some test float data to a buffer and reads them back. You'll notice the numbers are not exactly equal since we're converting from JavaScript numbers (double-precision 64-bit binary format IEEE 754) to 32-bit floats.
const floatSizeBytes = 4;
const floatCount = 10;
const buf = Buffer.alloc(floatCount * floatSizeBytes);
const testFloats = Array.from({ length: floatCount }, (v,k) => Math.random() * 100);
console.log("Test floats:", testFloats);
for(let i = 0; i < floatCount; i++) {
buf.writeFloatLE(testFloats[i], i * floatSizeBytes);
}
console.log("Buffer (raw):", buf);
function readFloat(buffer, offset, littleEndian = true) {
if (littleEndian) {
return buffer.readFloatLE(offset);
} else {
return buffer.readFloatBE(offset);
}
}
function bufferToFloatArray(buffer, littleEndian = true) {
const length = Math.floor(buffer.length / floatSizeBytes);
return Array.from( { length }, (v, k) => readFloat(buffer, k * floatSizeBytes, littleEndian));
}
console.log("Read back floats from buffer:", bufferToFloatArray(buf, true));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…