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

时间:2020-09-30 19:20:56

标签: java plc

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

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

PLC中的74.81565被转换为低16位:-24163和高16位: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

1 个答案:

答案 0 :(得分:0)

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

相关问题