Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float to binary in C++

I'm wondering if there is a way to represent a float using a char in C++?

For example:

int main()  
{  
    float test = 4.7567;  
    char result = charRepresentation(test);  
    return 0;  
}  

I read that probably using bitset I can do it but I'm not pretty sure.

Let's suppose that my float variable is 01001010 01001010 01001010 01001010 in binary.

If I want a char array of 4 elements, the first element will be 01001010, the second: 01001010 and so on.

Can I represent the float variable in a char array of 4 elements?

like image 519
Eric Avatar asked Dec 22 '22 03:12

Eric


2 Answers

I suspect what you're trying to say is:

int main()  
{  
    float test = 4.7567; 
    char result[sizeof(float)];

    memcpy(result, &test, sizeof(test));

    /* now result is storing the float,
           but you can treat it as an array of 
           arbitrary chars

       for example:
    */
    for (int n = 0; n < sizeof(float); ++n) 
        printf("%x", result[n]);

    return 0;  
}  

Edited to add: all the people pointing out that you can't fit a float into 8 bits are of course correct, but actually the OP is groping towards the understanding that a float, like all atomic datatypes, is ultimately a simple contiguous block of bytes. This is not obvious to all novices.

like image 179
egrunin Avatar answered Jan 04 '23 23:01

egrunin


the best you can is create custom float that is byte size. or use char as fixed point decimal. on all cases this will lead to significant loss of precision.

like image 22
Andrey Avatar answered Jan 05 '23 00:01

Andrey