admin管理员组

文章数量:1180512

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?

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?

Share Improve this question asked Mar 9, 2017 at 15:25 Michael BergmannMichael Bergmann 1231 gold badge1 silver badge4 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 24

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)

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

本文标签: JavaScript convert Array of 4 bytes into a float value from modbusTCP readStack Overflow