Convert 2 integer register values to float

I have a Modbus device which encodes a float across 2 registers which are 16 bit each. In C/C++ I would use a union but how to do this in TinyCLR?

For example, I get 49452 in the first register and 52489 in the second register. Data is encoded as IEEE754 single precision floating point and should be a vallue of -10.8xxxx. The Modbus library returns unsigned short.

Any ideas? I found a number of answers online but they all require the full C# stack to work. I need a TinyCLR version :wink:

I have had the same issue. Not sure it is best but I use Bitconverter.GetBytes() to copy the bytes into a 4-byte array. Then use Bitconverter.ToSingle() to get the floating-point value.

Ideally, the Modbus library could return the byte array instead of a ushort or ushort[].

I think I looked at extending the Modbus library to provide that functionality but didn’t complete it, but I will have to address it soon. I have a large application upcoming that will require large blocks of data to be read by Modbus. The data packet will contain multiple data types so having it as a byte array will make it easier to use BitConverter.


Thanks Steve. I’ll give it a try tonight.

Under Android I use a library called Modbus4J which includes functions to read float etc.

Hi Steve. Your suggestion worked perfectly. Thanks heaps.

1 Like