英文:
Convert PLC Modbus Signals to Float Value (pair of 16 bits integer into a 32 bit float)
问题
以下是您要求的代码部分的翻译:
public class HelloWorld {
public static void main(String[] args) {
short high = 17045; // 高16位
short low = -24163; // 低16位
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');
// 工作示例
short high1 = -16031; // 高16位
short low1 = 4680; // 低16位
int combined1 = (high1 << 16) | low1;
float num1 = Float.intBitsToFloat(combined1);
System.out.println(num1 + " " + combined1);
}
}
请注意,我只翻译了代码部分,其他内容不包括在内。如果您有任何进一步的问题或需要帮助,请随时提问。
英文:
I am trying to convert values from Modbus addresses on a PLC to a float value on my program. Inside the PLC, the value is represented as 32 bit float, but to send it through Modbus, they convert it to pair of 16 bit integers. Now when I retrieve the value, I have to convert them back to 32 bit float. I already have working code (in the picture), but some low bit values are represented with '-' first and I can't convert them. Does anyone know how I should deal with this?
**For Example: -14.066963 in PLC is converted into low 16bit: 4680 and high 16bit: -16031. I can convert this back to its original value.
74.81565 in PLC is converted into low 16bit: -24163 and high 16bit: 17045. I can't convert this back to its original value.**
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);
}
}
答案1
得分: 0
将 short 改为 int。使它们的值在无符号 short 的范围内,即 0 到 65535(而不是有符号 short 的范围 -32768 到 +32767)。您需要将负的 short 值更改为它们的无符号等价值(例如,-24163 更改为 41373)。我更倾向于在十六进制中进行所有这些操作,例如 0xA19D(而不是 -24163 或 41373),因为整数值是无意义的 - 实际上您正在生成 IEEE 754 32 位位模式。
英文:
Change the short's to int's. Make their values be in the range of an unsigned short 0..65535 (instead of signed short -32768..+32767). You will need to change your negative short values to their unsigned equivalent (e.g. -24163 to 41373). I prefer to do all this stuff in hexadecimal, e.g. 0xA19D (instead of -24163 or 41373), since the integer values are meaningless - it's really the IEEE 754 32-bit bit pattern you are generating
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论