Sunday, December 4, 2011

How to convert binary back to float?

I have a problem that I can't get my head around.





sizeof(float) is 4 bytes


I have read 4 bytes of data into memory


Now I need to convert these 4 bytes into a variable of type float.





How do I go about doing this?





Please help.|||union float_bytes


{


float f;


char b[4];


} fb;





int main()


{


float f;


fb.b[0] = ...; /* fill in value */


fb.b[1] = ...; /* fill in value */


fb.b[2] = ...; /* fill in value */


fb.b[3] = ...; /* fill in value */


f = fb.f;


/*...use f now...*/


return 0;


}





That's one approach, another even simpler approach is to just cast a pointer to the 4 byte-array to a pointer to a float, then read from that pointer:





char b[4];


float f;


/*fill in b*/


f = *((float*)b);


/*use f*/





You will want to make sure the 4 bytes involved were generated by decomposing a valid float value using similar techniques (using a union or casting). Otherwise garbage will most likely be the result.

No comments:

Post a Comment