js实现modbus_JavaScript将4字节的数组转换为modbusTCP读取的浮点值

这篇博客探讨了如何将从ModbusTCP响应中获取的4字节数组转换为浮点数值。通过创建ArrayBuffer和DataView,使用DataView的setUint8方法设置字节,然后使用getFloat32读取浮点值,最终得出约7.0的数值。
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值