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 badges3 Answers
Reset to default 24You 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
版权声明:本文标题:JavaScript convert Array of 4 bytes into a float value from modbusTCP read - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738125454a2065016.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论