How to convert float number to Binary?

前端 未结 6 813
不思量自难忘°
不思量自难忘° 2020-12-07 16:53

Can anyone please tell me how can I convert this float number: 12.25 to binary? I know how to convert the \"12\" but not the 0.25

Any help is much appreciated. Thank

6条回答
  •  萌比男神i
    2020-12-07 17:31

    The float value is stored in IEEE 754 format so we can't convert it directly like integer, char to binary.

    But we can convert float to binary through a pointer.

    #include 
    
    int main()
    {
        float a = 7.5;
        int i;
        int * p;
    
        p = &a;
        for (i = sizeof(int) * 8 - 1; i >= 0; i--)
        {   
            printf("%d", (*p) >> i & 1); 
        }   
    
        return 0;
    }
    

    Output

    0 10000001 11100000000000000000000
    

    Spaces added for clarification, they are not included as part of the program.

提交回复
热议问题