简体   繁体   English

IEEE 754用C语言转换为十进制

[英]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) 我正在寻找将浮点数转换为C中十进制表示形式的最佳方法。我将尝试举一个例子:用户在IEEE754中引入一个数字(1 1111111 10101 ...),程序必须返回小数表示形式(例如25.6)
I've tried with masks, and bitwise operations, but I haven't got any logical result. 我尝试使用掩码和按位运算,但是没有任何逻辑结果。

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. 我将int用作中间表示形式,因为它的位数与浮点数(在我的机器上)相同,并且允许从二进制字符串轻松转换。

#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 . 正如@DanielKamilKozar指出的那样,该int的正确类型是uint32_t However, that would require including <stdint.h> . 但是,这需要包含<stdint.h>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM