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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With