1

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?

Community
  • 1
  • 1
Dzung Nguyen
  • 3,794
  • 9
  • 48
  • 86

1 Answers1

2

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

Edit:

There is another solution, which will work also on modern browser environments:

function intToFloat(integer) {
    let intArray = new Uint32Array([ integer ]);
    let floatArray = new Float32Array(intArray.buffer);
    return floatArray[0];
}
qzb
  • 8,163
  • 3
  • 21
  • 27