将 PLC Modbus 信号转换为浮点值(一对 16 位整数转换为 32 位浮点数)

Convert PLC Modbus Signals to Float Value (pair of 16 bits integer into a 32 bit float)

我正在尝试将 PLC 上的 Modbus 地址值转换为程序中的浮点值。在 PLC 内部,该值表示为 32 位浮点数,但要通过 Modbus 发送它,它们会将其转换为一对 16 位整数。现在,当我检索值时,我必须将它们转换回 32 位浮点数。我已经有了工作代码(在图片中),但是一些低位值首先用“-”表示,我无法转换它们。有谁知道我该如何处理?

**例如:PLC中的-14.066963转换为低16位:4680和高16位:-16031。我可以将其转换回其原始值。

74.81565在PLC中被转换成低16bit:-24163和高16bit:17045,我不能把它转换回原来的值**

public class HelloWorld{

 public static void main(String []args){
    short high = 17045; // the high 16 bits
    short low = -24163; // the low 16 bits
    int first_part = high << 16; 
    int second_part = first_part | low;
    
    float num = Float.intBitsToFloat(second_part);
    System.out.println(first_part + " " + second_part + " " + num + '\n');
    
    
    
    
    //Working values
    short high1 = -16031; // the high 16 bits
    short low1 = 4680; // the low 16 bits
    int combined1 = (high1 << 16) | low1;
    
    float num1 = Float.intBitsToFloat(combined1);
    System.out.println(num1 + " " + combined1);
 }

}

Picture example

将 short 更改为 int。使它们的值在 unsigned short 0..65535 范围内(而不是 signed short -32768..+32767)。您需要将负的短值更改为其无符号等效值(例如 -24163 至 41373)。我更喜欢用十六进制来做所有这些事情,例如0xA19D(而不是 -24163 或 41373),因为整数值没有意义 - 它实际上是您生成的 IEEE 754 32 位位模式