Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

javascript - 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

question from:https://stackoverflow.com/questions/65952975/converting-presentation-of-a-buffer-from-int8-to-float32-in-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...