10

I'am trying to convert a array of 4 bytes to a float value. Here is the thing:

I get an answer from my request via ModbusTCP, this looks something like this:

{ "data": [ 16610, 40202 ], "buffer": { "type": "Buffer", "data": [ 64, 226, 157, 10 ] } }

This string is converted into a json-object, parsed and accessed with

var ModbusArray = JSON.parse(msg.payload);
var dataArray = ModbusArray.buffer.data;

(the msg.payload comes from node red)

Until here it works find. The Array represents a floating value. In this case it should be a value of around 7.0.

So, here is my Question: how can I get a float from this dataArray?

Michael Bergmann
  • 103
  • 1
  • 1
  • 4

3 Answers3

22

You could adapt the excellent answer of T.J. Crowder and use DataView#setUint8 for the given bytes.

var data =  [64, 226, 157, 10];

// Create a buffer
var buf = new ArrayBuffer(4);
// Create a data view of it
var view = new DataView(buf);

// set bytes
data.forEach(function (b, i) {
    view.setUint8(i, b);
});

// Read the bits as a float; note that by doing this, we're implicitly
// converting it from a 32-bit float into JavaScript's native 64-bit double
var num = view.getFloat32(0);
// Done
console.log(num);
Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 2
    Be warned: getFloat32() does not give the expected 6~9 significant digits of a 32-bit floating point number... instead it is lazy and doesn't round at all, giving you the 17 digits of a double. So make sure you round off at 6 or 7 sigdigs manually after using getFloat32() or you may get extra digits due to getFloat32() incorrectly equivating the precision of a single's 23-bit mantissa onto a double's 52-bit mantissa. – James Oct 02 '18 at 22:55
8

For decoding a float coded in Big Endian (ABCD) with Node.js:

Buffer.from([ 64, 226, 157, 10 ]).readFloatBE(0)
Bruno L.
  • 457
  • 6
  • 8
0

No need to copy data in a loop :

var data =  [64, 226, 157, 10];

// Create a buffer
var buf = new Uint8Array(data).buffer
// Create a data view of it
var view = new DataView(buf);

var num = view.getFloat32(0);
// Done
console.log(num);
Remy Mellet
  • 1,675
  • 20
  • 23