Float to binary in C++

后端 未结 7 1342
孤独总比滥情好
孤独总比滥情好 2020-12-09 07:29

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 =         


        
相关标签:
7条回答
  • 2020-12-09 08:10

    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.

    0 讨论(0)
提交回复
热议问题