0

I am reading data from an energy meter over modbus protocol and I am getting hex values from there. I want to convert that hex string to floating point value. For example - 0x416f0000 denotes a value of 14.9375.Reference

Can anyone please help me how to do it on Arduino IDE?

  • You mean Modbus ASCII, right? Non-ASCII Modbus doesn't use hex. – Edgar Bonet Dec 11 '18 at 10:32
3

If you do indeed have an ASCII string of hexadecimal numbers (and not a raw binary float), then your best option may be to do the conversion in two steps:

  1. convert the string to a 32 bit unsigned number using strtoul()
  2. reinterpret the binary pattern of this integer as a float.

For example, the following program:

void setup() {
    const char modbus_data[] = "416F0000";
    union {
        uint32_t i;
        float f;
    } data;
    data.i = strtoul(modbus_data, NULL, 16);

    Serial.begin(9600);
    Serial.println(data.f, 4);
}

void loop(){}

prints 14.9375.

Note that for strtoul() to function properly, the hex string must be followed by a character that is not a valid hex digit (a \0 in the example above).

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.