Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

floating point - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...