I am transferring data from Arduino via serial port to a Java application on a Mac. I am using the Modbus protocol, and need to transfer floats. As the Modbus requires INTs, I have to split the float (32 bits) into two ints like this:
Code: Select all
void floatToInts(float f, int *msb, int *lsb) {
byte byte_array[4];
memcpy( byte_array, &f, sizeof(f) );
memcpy( lsb, &byte_array[2], 2);
memcpy( msb, &byte_array[0], 2);
}
However, I am having problems reassembling them into a float in Java.
I have found the Float.intBitsToFloat function, but I have not had any great success with it. Here is how I use it:
// LSB is in index 0 and MSB is in index 1
Float.intBitsToFloat(res.getRegisterValue(0) << 16 | res.getRegisterValue(1))
This works if my MSB is zero (in the case, for example, where I have a float of 36.5, I have LSB = 0x4212 and MSB = 0x000). However, if the MSB is non zero, it gives out junk...
Anybody ever encounter this and have a solution?
Thanks