Search code examples
cfloating-pointieee-754

Is IEEE-754 representation used in C?


I have to encode the electron charge, which is -1.602*10-19 C, using IEEE-754. I did it manually and verified my result using this site. So I know my representation is good. My problem is that, if I try to build a C program showing my number in scientific notation, I get the wrong number.

Here is my code:

#include <stdio.h>
int main(int argc, char const *argv[])
{
    float q = 0xa03d217b;
    printf("q = %e", q);
    return 0;
}

Here is the result:

$ ./test.exe
q = 2.688361e+09

My question: Is there another representation that my CPU might be using internally for floating point other than IEEE-754?


Solution

  • The line float q = 0xa03d217b; converts the integer (hex) literal into a float value representing that number (or an approximation thereof); thus, the value assigned to your q will be the (decimal) value 2,688,360,827 (which is what 0xa03d217b equates to), as you have noted.

    If you must initialize a float variable with its internal IEEE-754 (HEX) representation, then your best option is to use type punning via the members of a union (legal in C but not in C++):

    #include <stdio.h>
    
    typedef union {
        float f;
        unsigned int h;
    } hexfloat;
    
    int main()
    {
        hexfloat hf;
        hf.h = 0xa03d217b;
        float q = hf.f;
        printf("%lg\n", q);
        return 0;
    }
    

    There are also some 'quick tricks' using pointer casting, like:

    unsigned iee = 0xa03d217b;
    float q = *(float*)(&iee);
    

    But, be aware, there are numerous issues with such approaches, like potential endianness conflicts and the fact that you're breaking strict aliasing requirements.