Dzung Nguyen Dzung Nguyen - 3 months ago 10
C Question

Node.JS deserialize floats at uneven offset

This question relates to my previous ones:

Nodejs buffer bitwise slicing

I transmit data through bluetooth LE to a node.js server. Here is the format of serialized data:

top: 10 bit (unsigned integer)
bottom: 10 bit (unsigned integer)
accelerometerX: 23 bit (truncated 32-bit floating point)
accelerometerY: 23 bit
...


Data is received as a node.js buffer. I'm able to parse top and bottom as they are integers, and I can use shift operation on them.

top = data.readUInt16LE() & 0x3FF;
bottom = data.readUInt16LE(1);
bottom = (bottom >> 2) & 0x3FF;

accX = data.readUInt32LE(2);
accX = ((accX >> 4) & 0x7FFFFFF) << 9;


However, for accX are floats. I can't use ReadFloat32LE from node.js as it's not byte aligned. So now I'm reading as uint32, shift it back with 9 least significant digits. How do I get float from its bit representation in NodeJS?

qzb qzb
Answer

It's not a pretty solution, but you can use another buffer to make such conversion:

function intToFloat(integer) {
    let buf = Buffer.alloc(4);
    buf.writeUInt32LE(integer);
    return buf.readFloatLE();
}