IEEE-754表示是否在C中使用?

我必须使用 IEEE-754对电子电荷进行编码,即 -1.602*10 -19 C。我手动完成并使用此站点验证了我的结果。所以我知道我的代表是好的。我的问题是,如果我尝试构建一个以科学记数法显示我的数字的 C 程序,我会得到错误的数字。

这是我的代码:

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

结果如下:

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

我的问题:除了 IEEE-754 之外,还有其他表示我的 CPU 可能在内部用于浮点吗?

回答

float q = 0xa03d217b;转换的整数(十六进制)字面float表示该数(或其近似值)值; 因此,分配给您qwill的值是(十进制)值2,688,360,8270xa03d217b相当于),正如您所指出的。

如果您必须float使用其内部 IEEE-754 (HEX) 表示初始化变量,那么您最好的选择是通过 a的成员使用类型双关 (在 C 中合法,但在 C++ 中合法):union

#include <stdio.h>

typedef union {
    float f;
    unsigned int h;
} hexfloat;

int main()
{
    hexfloat hf;
    hf.h = 0xa03d217b;
    float q = hf.f;
    printf("%lgn", q);
    return 0;
}

还有一些使用指针转换的“快速技巧”,例如:

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

但是,请注意,此类方法存在许多问题,例如潜在的字节顺序冲突以及您违反了严格的别名要求的事实。

  • You can avoid the aliasing problems by using a `union`, and I've never seen nor heard of a machine that uses different endianness for ints and floats, but it is technically possible. More likely is a machine that uses non-IEEE fp, though those are rare these days.

以上是IEEE-754表示是否在C中使用?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>