Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  76] [ 6]  / answers: 1 / hits: 17826  / 7 Years ago, thu, march 9, 2017, 12:00:00

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?


More From » javascript

 Answers
23

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




[#58611] Tuesday, March 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yulisa

Total Points: 436
Total Questions: 102
Total Answers: 123

Location: Palau
Member since Tue, May 30, 2023
1 Year ago
yulisa questions
Sun, Jun 20, 21, 00:00, 3 Years ago
Wed, Apr 14, 21, 00:00, 3 Years ago
Fri, Aug 7, 20, 00:00, 4 Years ago
Mon, Mar 23, 20, 00:00, 4 Years ago
;