c - C语言中的IEEE 754转十进制

标签 c bit-manipulation decimal transform ieee-754

我正在寻找将 float 转换为其在 C 中的十进制表示的最佳方法。我将尝试给您举个例子:用户在 IEEE754 中引入一个数字(1 1111111 10101 ...)和程序必须返回十进制表示形式(例如 25.6)
我试过掩码和按位运算,但没有得到任何合乎逻辑的结果。

最佳答案

我相信以下正在执行您描述的操作:

我使用 int作为中间表示,因为它与 float (在我的机器上)具有相同的位数,并且允许从二进制字符串轻松转换。

#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;
}

正如@DanielKamilKozar 指出的那样,int 的正确类型是uint32_t .但是,这需要包括 <stdint.h> .

关于c - C语言中的IEEE 754转十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33111671/

相关文章:

c++ - 为 arm mov 获取有效 imm num 的快速方法?

c - 我应该使用哪种数据类型来存储 C 语言中的变量 10^200?

mysql - 为用户处理已读/未读帖子,例如 mysql 中的邮件

c++ - 我想根据任意掩码打包这些位

sql-server - T-SQL 中的位翻转操作

Golang : how can I convert a float64 currency representation to the lowest denomination?(乘以 100 不适用于所有货币)

Java NumberFormatException?

C - 动态矩阵分配 : something doesn't make sense to me

java - java中的十进制输入edittext

c - 当在由结构组成的树上使用 qsort() 时,我没有收到排序后的数组