Why Isn't My Floating Point Values Printing Properly?

前端 未结 4 2008
-上瘾入骨i
-上瘾入骨i 2021-01-24 07:50

I am trying to print out the floating point values 0x40a00000 and 0xc0200000. But the values that I print out and the correct values according to the IEEE-754 Floating Point Con

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-24 08:14

    These are assigning the float representation of the hexadecimal numbers to the floats.

    Instead, do this:

    int i1 = 0x40a00000;
    int i2 = 0xc0200000;
    float tmp1, tmp2;
    memcpy(&tmp1, &i1, sizeof(int));
    memcpy(&tmp2, &i2, sizeof(int));
    

    Print them:

    printf("tmp1 = %.2f\n", tmp1);
    printf("tmp2 = %.2f\n", tmp2);
    

    Output:

    tmp1 = 5.00
    tmp2 = -2.50

    Full example:

    #include 
    #include 
    
    int main(void)
    {
        int i1 = 0x40a00000;
        int i2 = 0xc0200000;
        float tmp1, tmp2;
        memcpy(&tmp1, &i1, sizeof(int));
        memcpy(&tmp2, &i2, sizeof(int));
        printf("tmp1 = %.2f\n", tmp1);
        printf("tmp2 = %.2f\n", tmp2);
    }
    

提交回复
热议问题