Search code examples
cnumber-formatting

printf does not print correct float value


I have a 4byte hex number, when I convert it to float it is -0.5(I checked references and it's correct), but printf gives very wrong value:

 int f=0xBF000000;
 printf("%f",(float)f);  // prints -1090519040.000000

I can't figure out what is wrong here! All calculators give the correct value as -0.5, but printf gives above value.


Solution

  • Your int has the value -1090519040. If you print it you get this value:

    printf("%d", f); // -1090519040
    

    If you typecast it to float, it will take this value and change the type but not the value. So it will result in -1090519040.0000.

    If you actually want to interpret your int as a float, you can use a pointer:

    float* p = &f;
    printf("%f",*p); // -0.500000
    

    Here you have a float pointer that points to the address of your integer and if you print it it will interpret the bits as a float.

    Comment from Eric Postpischil:

    float *p = &f; is not a proper way to reinterpret the bytes of an object in C, as it violates the aliasing rule (C 2011 [N1570] 6.5 7, an object’s value shall be accessed only through its effective type, a character type, or certain others).

    Another (better) way would be to use memcopy and copy your int into another float:

    int a = 0xBF000000;
    float b = 0;
    memcpy(&b, &a, 4);
    printf("%f", b); // -0.500000