Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a float to a 4 byte char in C?

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 ?

like image 624
12oni Avatar asked Aug 16 '13 10:08

12oni


People also ask

Can we convert float to char in C?

gcvt() | Convert float value to string in C h header file. This function is used to convert a floating point number to string. Syntax : gcvt (float value, int ndigits, char * buf); float value : It is the float or double value.

Can we convert float to byte?

As we know, the size of a float in Java is 32 bit which is similar to an int. So we can use floatToIntBits or floatToRawIntBits functions available in the Float class of Java. And then shift the bits to return a byte array.

Is a byte a char in C?

char is 1 byte in C because it is specified so in standards. The most probable logic is. the (binary) representation of a char (in standard character set) can fit into 1 byte.

Is char same as byte?

3) Another difference between char and byte is that char is a larger data type than a byte. The range of byte is between -128 to 127 but the range of char is from 0 to 65535 because a byte is a signed 8-bit data type and char is an unsigned 16-bit data type hence, its maximum value is 2 ^ 16 - 1 which is 65535.


2 Answers

Just use memcpy:

#include <string.h>

float f = 2.45f;
char a[sizeof(float)];

memcpy(a, &f, sizeof(float));

If you require the opposite endianness then it is a trivial matter to reverse the bytes in a afterwards, e.g.

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;
}
like image 102
Paul R Avatar answered Nov 11 '22 07:11

Paul R


You have a few ways of doing this, including these two:

  1. 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".

  2. 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.

like image 42
Some programmer dude Avatar answered Nov 11 '22 07:11

Some programmer dude