Convert Float to Integer Representation using C

Convert Float to Integer Representation using C

When working with low-level programming, comparing floating-point values, or debugging precision issues, it's often helpful to examine the raw binary representation of floating-point numbers. In C, this can be done by reinterpreting a float or double as an unsigned integer, allowing direct access to the underlying IEEE 754 bit pattern that represents the value in memory.

To convert a floating-point number to its raw binary representation in C, the code uses a union, which allows two different types to share the same memory. This technique, known as type-punning, enables the program to assign a float (or double) to one member of the union and read from another member of a different type, such as unsigned int (or unsigned long long). This effectively reinterprets the underlying bits of the floating-point value as an integer without altering the data or invoking undefined behavior. It's a common and safe method in C for examining the exact IEEE 754 bit layout of floating-point numbers. The program then prints the resulting integer values, which represent the raw binary form of 1.0f and 1.0.

#include <stdio.h>

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

    return u.i;
}

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

    return u.i;
}

int main() {
    printf("%u\n", asuint(1.0f)); // 1065353216
    printf("%llu\n", asuint64(1.0)); // 4607182418800017408

    return 0;
}

Leave a Comment

Cancel reply

Your email address will not be published.