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);
}
}
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