ccastingtype-conversionlong-integerunsigned-long-long-int

How to convert unsigned long long to float/int in C?


An unsigned long long variable has the value of "40 36 70 A3 D7 0A 3D 71" in hex. If I print it with the %fconversion specifier I get the right conversion from IEEE-754. How can I cast this variable to a floating one or int, even if I lose some decimals?

I have tried casting it but it gives me bad values. Example here:

unsigned long long hex = 0x403670A3D70A3D71;
float cast_float = (float)hex;

Solution

  • Assuming that the unsigned long long variable contains a value that is a valid double value, then you could use type punning, for example using unions:

    union
    {
        unsigned long long i;
        double             f;
    } value = { .i = 0x403670A3D70A3D71 };
    
    printf("0x%llx is %f\n", value.i, value.f);
    

    Note that this is valid only if the value in the integer have the same bit-pattern as a valid double-precision floating point value on your system. Otherwise it could lead to undefined behavior.


    Now if you want to convert it to the int value 22 (as 0x403670A3D70A3D71 is the binary representation of the double value 22.44), then you first need to use type-punning to get the floating point value, then use the floor function to truncate it to an integer value (but still in floating point type), and lastly cast that to an int:

    int int_val = (int) floor(value.f);