How to convert a float to a 4 byte char in C?
c, char, type-conversion
Solution
You have a few ways of doing this, including these two:
Use typecasting and pointers:
float f = 2.45;
char *s = (char *) &f;
Note that this isn't safe in any way and that there is no string terminator after the "string".
Use a `union`:
union u
{
float f;
char s[sizeof float];
};
union u foo;
foo.f = 2.45;
The char array can now be accessed to get the byte values. Also note like the first alternative there is no string terminator.
Problem
I want to convert a float number for example 2.45 to the 4 byte char array. so the 2.45 should look like this `'@' 'FS' 'Ì' 'Í'` which is binary the ieee representation of `2.45 = 01000000 00011100 11001100 11001101`? I've solved the problem but it has a bad complexity. do you have any good ideas? Thanks for the good answers. can you please tell me the way back from the char array to the float number ?