简体   繁体   English

将寄存器值转换为 float 32 big endian

[英]Convert register values to float 32 big endian

I have two signed register values 17147 and -27394.我有两个带符号的寄存器值 17147 和 -27394。 They are in order of High-Low bits.它们按高位到低位的顺序排列。 I want to get the value float 32 big endian value using these value.我想使用这些值获得值 float 32 big endian 值。 I have used following code to convert to value.我使用以下代码转换为值。

My code我的代码

int intValue = 17147;
intValue <<= 16;
intValue += -27394;
byte[] bytes = BitConverter.GetBytes(intValue);
double readingValue = BitConverter.ToSingle(bytes, 0);

According to above code reading shows as 125.291 .根据上面的代码阅读显示为125.291 But modbus tools & other online convertions says that value should be 125.791 .但是 modbus 工具和其他在线转换表明该值应该是125.791

Please note that some times reading is okay for some values.请注意,有时读取某些值是可以的。 Actual value and converted value difference is not the same.实际值和转换值的区别是不一样的。

You're combining the two registers together incorrectly.您错误地将两个寄存器组合在一起。

  • 17147 is hex 42 FB (or 00 00 42 FB as a 4-byte value) 17147 是十六进制42 FB (或00 00 42 FB作为 4 字节值)
  • -27394 is hex 94 FE as a 2-byte value, or FF FF 94 FE as a 4-byte value -27394 是作为 2 字节值的十六进制94 FE ,或作为 4 字节值的FF FF 94 FE
  • Therefore intValue should have the hex value 42 FB 94 FE , but your way of combining 42 FB and 94 FE gives you 42 FA 94 FE .因此intValue应该有十六进制值42 FB 94 FE ,但是你结合42 FB94 FE的方式给你42 FA 94 FE

You're being caught out by the fact that -27394 is presented as a negative number, but that's just the way that your software has chosen to interpret those 2 bytes.您被 -27394 显示为负数这一事实所困扰,但这正是您的软件选择解释这 2 个字节的方式。 You're then treating it as a signed 4-byte value rather than an unsigned 2-byte value when you come to combine it with the 17147.然后,当您将它与 17147 组合时,您会将其视为带符号的 4 字节值而不是无符号的 2 字节值。

When we combine 17147 and -27394, we need to make sure that we just look at the lower 2 bytes of each.当我们组合 17147 和 -27394 时,我们需要确保只查看每个的低 2 个字节。 That will undo any damage that was done by interpreting the values as signed 4-byte numbers.这将撤消通过将值解释为带符号的 4 字节数字而造成的任何损坏。

int upper = 17147;
int lower = -27394;
int intValue = ((upper & 0xFFFF) << 16) | (lower & 0xFFFF);

Now:现在:

byte[] bytes = BitConverter.GetBytes(intValue);
double readingValue = BitConverter.ToSingle(bytes, 0);
Console.WriteLine(readingValue);

Gives 125.79100036621094, as expected.正如预期的那样,给出 125.79100036621094。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM