JavaScript convert Array of 4 bytes into a float value from modbusTCP read

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

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

Buffer.from([ 64, 226, 157, 10 ]).readFloatBE(0)

Tags:

Javascript