Search code examples
cbit-manipulationdecimaltransformieee-754

IEEE 754 to decimal in C language


I'm looking the best way to transform a float number to its decimal representation in C. I'll try to give you an example: the user introduces a number in IEEE754 (1 1111111 10101...) and the program has to return the decimal representation (ex. 25.6)
I've tried with masks, and bitwise operations, but I haven't got any logical result.


Solution

  • I believe the following is performing the operation you describe:

    I use the int as an intermediate representation because it has the same number of bits as the float (on my machine), and it allowed easy conversion from the binary string.

    #include <stdio.h>
    
    union {
        int i;
        float f;
    } myunion;
    
    int binstr2int(char *s)
    {
        int rc;
        for (rc = 0; '\0' != *s; s++) {
            if ('1' == *s) {
                rc = (rc * 2) + 1;
            } else if ('0' == *s) {
                rc *= 2;
            } 
        }
        return rc;
    }
    
    int main(void) {
    
        // the input binary string (4 bytes)
        char * input = "11000000110110011001100110011010";
        float *output;
    
    
        // convert to int, sizeof(int) == sizeof(float) == 4
        int converted = binstr2int(input); 
    
        // strat 1: point memory of float at the int
        output = (float*)&converted; // cast to suppress warning
        printf("%f\n", *output); // -6.8
    
        // strat 2: use a union to share memory 
        myunion.i = converted; 
        printf("%f\n", myunion.f); // -6.8
    
        return 0;
    }
    

    As @DanielKamilKozar points out, the correct type for that int is uint32_t. However, that would require including <stdint.h>.