Search code examples
javaalgorithmfloating-pointintmodbus

Two 16 bit ints to One 32 bit float value


I am able to extract values from modbus as 16-bit shorts (unsigned) or as ints (should be treated as 16-bit words). I am tasked to combine two values to create a single 32 bit float value using java.

some example values I observed using a gui program:

  • int + int = float
  • 0 + 16256 = 1
  • 0 + 17096 = 100
  • 0 + 17097 = 100.5
  • 0 + 17530 = 1000
  • 8192 + 17530 = 1000.5

I attempted bit wise operators but that didn't seem to do the trick. leaves me scratching my head!


Solution

  • You can use Float.intBitsToFloat(int bits) to build a float from the bits of an int.

    short high = ... // the high 16 bits
    short low = ... // the low 16 bits
    int combined = (high << 16) | low;
    float num = Float.intBitsToFloat(combined);
    

    for example:

    short high = 17530;
    short low = 8192;
    

    produces the float 1000.5.