Dmitry
Dmitry

Reputation: 737

Converting presentation of a buffer from int8 to float32 in JS

In a buffer I have a sequence of bytes read from a file. And I need to represent them as a sequence of float32. Size of each file data block is about 15KB so I don't want to copy from this buffer to another. I've read a lot regarding Float32Array.from, for instance, here. In the resulting presentation figures changes, but they are still integer and their number still the same.

The code:

console.log('total points: ' + res.trans.length);
console.dir(res.trans);
console.log(Float32Array.from(res.trans));
console.log('total float points: ' + Float32Array.from(res.trans).length);

The result:

total points: 9504
Buffer(9504) [Uint8Array] [ 187,  97,  63, 187, 205, 183, 
Float32Array(9504) [ 187,  97,  63, 187, 205,...
total float points: 9504

In a browser:

enter image description here

Upvotes: 1

Views: 614

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30685

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));

Upvotes: 1

Related Questions