Search code examples
pointerscastingunsigned

Cast, pointers, unsigned, output


float f = 010; unsigned *pi = (unsigned *) &f; printf("%x", *pi); I don't understand why is output 41000000.


Solution

  • lets break this down into individual steps.

     float f = 010; 
    

    this sets f to 8.0 (!) because 010 is in octal.

    lets see what gets stored in memory, using my vs debugger I see

    enter image description here

    Why, well this is how 8.0 is stored in binary floating point. See https://www.h-schmidt.net/FloatConverter/IEEE754.html for a tool which will show you the binary representation of any float. Look here for a definition of the format https://en.wikipedia.org/wiki/Single-precision_floating-point_format.

    next you say

    float *pf = &f;
    

    ok take the address of f

     unsigned* pi = (unsigned*)pf;
    

    now treat the pointer to a float as though it were a pointer to an int. Nothing gets changed in f, we just get a pointer that thinks its pointing at an unsigned (32 bit) integer

     unsigned i = *pi;
    

    deference that pointer. i gets loaded with the four bytes in f.

    printf("%x", i);
    

    print that , in hex, treating those bytes as an int.

    so you get 41000000 cos thats what those bytes contain.

    check out this for an interesting video that shows this trick in action https://www.youtube.com/watch?v=p8u_k2LIZyo