使用缓冲区 nodejs 构建浮点值
Building float values using buffer nodejs
我正在读取 2x16 位形式的 32 位浮点数。构建值我正在尝试使用 Nodejs Buffer 函数,如下所示:
// Create new Buffer based on array bytes
var buf = Buffer.from([0x122f, 0x3A53]);
// Represent these bytes as 32-bit unsigned int
const value = buf.readUInt32BE();
// save the value
msg.payload = value;
return msg;
我 运行 在 Node-red 上,我收到以下错误:
RangeError [ERR_BUFFER_OUT_OF_BOUNDS]: Attempt to write outside buffer bounds
知道我做错了什么吗?
提前致谢!
更新
@hardillb 回答后,错误已经解决,但是,我仍然可以获得浮点值?
这是我得到的:
所以问题是如何构建浮出那 2 个 uint16。
问题在于您如何定义缓冲区。 Buffer.from()
需要一个 array of bytes,而不是 2 个 16 位数字
您可以通过将 16 位数字写入新缓冲区来实现,例如
var buf = Buffer.alloc(4);
buf.writeUInt16BE(0x122f);
buf.writeUInt16BE(0x3a53);
msg.payload = buf.readUInt32BE();
return msg;
从 msg.payload
中已有的 16 位值数组构建它
var buf = Buffer.alloc(msg.payload.length * 2)
for (var i=0; i< msg.payload.length); i++) {
buf.writeUInt16BE(msg.payload[i], (i*2));
}
msg.payload = buf.readUInt32BE();
return msg;
我正在读取 2x16 位形式的 32 位浮点数。构建值我正在尝试使用 Nodejs Buffer 函数,如下所示:
// Create new Buffer based on array bytes
var buf = Buffer.from([0x122f, 0x3A53]);
// Represent these bytes as 32-bit unsigned int
const value = buf.readUInt32BE();
// save the value
msg.payload = value;
return msg;
我 运行 在 Node-red 上,我收到以下错误:
RangeError [ERR_BUFFER_OUT_OF_BOUNDS]: Attempt to write outside buffer bounds
知道我做错了什么吗? 提前致谢!
更新 @hardillb 回答后,错误已经解决,但是,我仍然可以获得浮点值? 这是我得到的:
所以问题是如何构建浮出那 2 个 uint16。
问题在于您如何定义缓冲区。 Buffer.from()
需要一个 array of bytes,而不是 2 个 16 位数字
您可以通过将 16 位数字写入新缓冲区来实现,例如
var buf = Buffer.alloc(4);
buf.writeUInt16BE(0x122f);
buf.writeUInt16BE(0x3a53);
msg.payload = buf.readUInt32BE();
return msg;
从 msg.payload
var buf = Buffer.alloc(msg.payload.length * 2)
for (var i=0; i< msg.payload.length); i++) {
buf.writeUInt16BE(msg.payload[i], (i*2));
}
msg.payload = buf.readUInt32BE();
return msg;