Search code examples
c++arduinomodbus

Converting 2 uint16_t to 32-float IEEE-754 fomat


I have a modbus devices which saves 32-bit float values in IEEE754 format. In arduino, which uses C ofcourse, I can retrieve those values seperated into two 16-bit values, which are returned in uint16_t values. (each register from the modbus device has 16-bits, so the value is split over two registers, but the library I use returns uint16_t).

I am now trying to figure out to get these two uint16_t's into 1 32-bit float, and I would like to get some help, because I am stuck at how to convert this into this type of value.

Thanks in advance for your help.

EDIT:

To clarify, here's a format image IEEE754


Solution

  • The only way around strict aliasing or invalid type-punning is really through the use of std::memcpy:

    uint16_t const value[2] = { low_word, high_word };  // Assuming little-endianness
    float f;
    
    std::memcpy(reinterpret_cast<void*>(&f), reinterpret_cast<void const*>(value), sizeof f);