转换32位无符号“真实”数据类型(分成两个16位有符号的单词)到JavaScript [英] Convert 32bit unsigned "Real" data type (splitted into two 16 bit signed words) to javascript

查看:1109
本文介绍了转换32位无符号“真实”数据类型(分成两个16位有符号的单词)到JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个32位无符号的实数值分成两个16位有符号的字(0-65535)值。例如:
Value1:18584
Value2:18081
实际值是:如何将它们转换为一个javascript数字?

20644.3

我正在寻找像back2Real(18584,18081)这样的函数,它返回20644.3。这些值来自modbus应用程序(NodeJS / modbus_stack)。 SPS / modbus服务器发送一个Real值分成两个字寄存器。

问候,
root66

  function uint16ToFloat32(low,high){
var buffer = new ArrayBuffer(4);
var intView = new Uint16Array(buffer);
var floatView = new Float32Array(buffer);

intView [0] =低;
intView [1] = high;
返回floatView [0];


函数float32ToUint16(value){
var buffer = new ArrayBuffer(4);
var intView = new Uint16Array(buffer);
var floatView = new Float32Array(buffer);

floatView [0] = value;
return [intView [0],intView [1]];


console.log(Converted ints to,uint16ToFloat32(18584,18081));
console.log(Converted float to,float32ToUint16(20644.297));

这是一个记录:

  $ node floatsplit.js 
已转换的整数为20644.296875
将浮动转换为[18584,18081]
$


i've got a 32 bit unsigned "Real" value splitted into two 16 Bit signed "Word" (0-65535) values. How do I convert them to a javascript number?

Example: Value1: 18584 Value2: 18081 The Real value is: 20644.3

I'm searching for a function like back2Real(18584, 18081) which returns 20644.3. The values come from a modbus application (NodeJS / modbus_stack). The SPS/modbus server sends a "Real" value splitted into two Word-registers.

Regards, root66

解决方案

You can use the new(ish) typed array functionality to simplify this.

function uint16ToFloat32(low, high) {
  var buffer = new ArrayBuffer(4);
  var intView = new Uint16Array(buffer);
  var floatView = new Float32Array(buffer);

  intView[0] = low;
  intView[1] = high;
  return floatView[0];
}

function float32ToUint16(value) {
  var buffer = new ArrayBuffer(4);
  var intView = new Uint16Array(buffer);
  var floatView = new Float32Array(buffer);

  floatView[0] = value;
  return [intView[0], intView[1]];
}

console.log("Converted ints to", uint16ToFloat32(18584, 18081));
console.log("Converted float to", float32ToUint16(20644.297));

Here's a transcript:

$ node floatsplit.js
Converted ints to 20644.296875
Converted float to [ 18584, 18081 ]
$

这篇关于转换32位无符号“真实”数据类型(分成两个16位有符号的单词)到JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆