Float to binary in C++

后端 未结 7 1390
孤独总比滥情好
孤独总比滥情好 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 07:53

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

    If we ignore that your float is a float and convert 47567 into binary, we get 10111001 11001111. This is 16 bits, which is twice the size of a char (8 bits). Floats store their numbers by storing a sign bit (+ or -), an exponent (where to put the decimal point, in this case 10^-1), and then the significant digits (47567). There's just not enough room in a char to store a float.

    Alternatively, consider that a char can store only 256 different values. With four decimal places of precision, there are far more than 256 different values between 1 and 4.7567 or even 4 and 4.7567. Since you can't differentiate between more than 256 different values, you don't have enough room to store it.

    You could conceivably write something that would 'translate' from a float to a char by limiting yourself to an extremely small range of values and only one or two decimal places*, but I can't think of any reason you would want to.

    *You can store any value between 0 and 256 in a char, so if you always multiplied the value in the char by 10^-1 or 10^-2 (you could only use one of these options, not both since there isn't enough room to store the exponent) you could store any number between 0 and 25.6 or 0 and 2.56. I don't know what use this would have though.

提交回复
热议问题