且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

转换IEEE 754浮点数与C十六进制 - 的printf

更新时间:2023-11-08 17:18:28

当你传递一个浮动作为参数传递给一个可变参数函数(如的printf()),它被提升到一个双击,这是两倍大一个浮动(至少在大多数平台)。

When you pass a float as an argument to a variadic function (like printf()), it is promoted to a double, which is twice as large as a float (at least on most platforms).

要解决这个问题将在浮动强制转换为单向unsigned int类型路过的时候它作为一个参数的printf()

One way to get around this would be to cast the float to an unsigned int when passing it as an argument to printf():

printf("hex is %x", *(unsigned int*)&f);

这也比较正确的,因为的printf()使用格式说明,以确定每个参数有多大。

This is also more correct, since printf() uses the format specifiers to determine how large each argument is.

从技术上讲,该方案违反了严格别名规则。您可以通过复制浮动的字节到 unsigned int类型并传送到的printf():

Technically, this solution violates the strict aliasing rule. You can get around this by copying the bytes of the float into an unsigned int and then passing that to printf():

unsigned int ui;
memcpy(&ui, &f, sizeof (ui));

printf("hex is %x", ui);

这两种解决方案是基于这样的假设的sizeof(int)的==的sizeof(浮点),这是在许多32位系统的情况下,但ISN 'T一定如此。

Both of these solutions are based on the assumption that sizeof(int) == sizeof(float), which is the case on many 32-bit systems, but isn't necessarily the case.