IEEE 754 to decimal in C language

房东的猫 提交于 2019-12-13 02:14:00

问题


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.


回答1:


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>.



来源:https://stackoverflow.com/questions/33111671/ieee-754-to-decimal-in-c-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!