11 years, 2 months ago.

how to convert 4 hex register to floating point via IEEE 754 floating point format

I'm communicating with a Modbus device that uses IEEE 754 floating point format. I'm trying to convert 4 different hex registers that i receive from device through getc() into a float variable using IEEE 754 format. I tried saving those hex register into char and convert it to float using union but the main problem is that for example 0x10 will be recognized as 10 in decimal instead of 16 in decimal.

For example, i receive 4 different hex register (43, 70, 80, 00 ). The output should be 240.5 but i got 0.

Incorrect value with this function.

union {
    char c[4];
    float f;
} conv;

Any solution for this?

1 Answer

11 years, 2 months ago.

I think you may be putting each byte into the char array backwards.

This is not mbed code, but shows that converting using a union like you're doing should work fine.

#include <stdio.h>
int main(int argc, char *argv[]) {
    union {
        char c[4];
        float f;
    } u;
    u.c[3] = 0x43;
    u.c[2] = 0x70;
    u.c[1] = 0x80;
    u.c[0] = 0x00;

    printf("%f\n", u.f);
}

This code prints 240.500000

If you change the order like this.

#include <stdio.h>
int main(int argc, char *argv[]) {
    union {
        char c[4];
        float f;
    } u;
    u.c[0] = 0x43;
    u.c[1] = 0x70;
    u.c[2] = 0x80;
    u.c[3] = 0x00;

    printf("%f\n", u.f);
}

Then it does print 0.000000.