How to convert float to 4 char bytes in C?

I want to convert a floating point number, for example 2.45, to an array of size 4 char bytes. so 2.45 should look like this: '@' 'FS' 'Ì' 'Í' , which is a binary representation of ieie 2.45 = 01000000 00011100 11001100 11001101 ?

I solved the problem, but it has poor complexity. do you have any good ideas?

Thanks for the good answers.

Could you tell me the way back from char array to floating point number?

+6
c char type-conversion
source share
2 answers

You have several ways to do this, including these two:

  • Use pointers and pointers:

     float f = 2.45; char *s = (char *) &f; 

    Note that this is in no way safe and that there is no line terminator after the line.

  • Use union :

     union u { float f; char s[sizeof float]; }; union u foo; foo.f = 2.45; 

    Now you can access the char array to get the byte values. Also notice how the first option has no line terminator.

+7
source share

Just use memcpy:

 #include <string.h> float f = 2.45f; char a[sizeof(float)]; memcpy(a, &f, sizeof(float)); 

If you need the opposite endianness, then the trivial question is to change the bytes in a subsequently, for example.

 int i, j; for (i = 0, j = sizeof(float) - 1; i < j; ++i, --j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; } 
+13
source share

All Articles