Need a IEEE754 format floating point formula format in C langauge

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.
<<code>>
union {
char c[4];
float f;
} conv;
<</code>>

Any solution for this?
Last edited on
Well, assuming that a float is 4 bytes and the machine is little-endian, you can do something like this:

1
2
3
4
5
6
7
8
9
10
11
union {
    char c[4];
    float f;
} conv;

conv.c[0] = 0x00;
conv.c[1] = 0x80;
conv.c[2] = 0x70;
conv.c[3] = 0x43;

// conv.f will be 240.5 here 


Or, the more ugly way:

1
2
3
4
5
6
7
char reg[4];
reg[0] = 0x00;
reg[1] = 0x80;
reg[2] = 0x70;
reg[3] = 0x43;

float f = *((float*)reg);
Is there any way i can do it instead of using char? Like using integer variable, etc?

My program consist of other function like CRC and bit shifting. My Modbus device always reply 0x10 as 10 hence using char is not ideal.
Last edited on
The reason for using char is that it is in effect an integer value which occupies one byte.

If you want to accept the user input as an integer that would be ok, during the assignment of int to char, the extra bits would simply be discarded.
Topic archived. No new replies allowed.