Convert Integer to Float Representation using C

Convert Integer to Float Representation using C

In low-level programming, especially when dealing with binary data formats or debugging floating-point precision issues, it's often useful to reinterpret an integer as a floating-point number. This is essentially the reverse of converting a float to its binary form - by starting with a known bit pattern (as an integer) and viewing it as a float or double.

In C, this can be safely accomplished using a union. A union allows multiple data types to occupy the same memory location, enabling type-punning: assigning a value to one member (e.g., an unsigned integer) and reading from another (e.g., a float). This technique reinterprets the bit pattern without invoking undefined behavior, making it ideal for examining or constructing floating-point values from raw binary. The code below demonstrates this technique by converting specific integer values into their floating-point equivalents. For example, the integer 1065353216 corresponds to the floating-point number 1.0f.

#include <stdio.h>

float asfloat(unsigned int i) {
    const union
    {
        unsigned int i;
        float f;
    } u = {i};

    return u.f;
}

double asdouble(unsigned long long i) {
    const union
    {
        unsigned long long i;
        double f;
    } u = {i};

    return u.f;
}

int main() {
    printf("%.7f\n", asfloat(1065353216)); // 1.0000000
    printf("%.7f\n", asdouble(4607182418800017408ULL)); // 1.0000000

    return 0;
}

Leave a Comment

Cancel reply

Your email address will not be published.