转换IEEE 754浮点数与C十六进制 - 的printf [英] Convert ieee 754 float to hex with c - printf
问题描述
在理想情况下以下code将采取浮动在IEEE 754重新presentation并将其转换为十六进制
Ideally the following code would take a float in IEEE 754 representation and convert it into hexadecimal
void convert() //gets the float input from user and turns it into hexadecimal
{
float f;
printf("Enter float: ");
scanf("%f", &f);
printf("hex is %x", f);
}
我也不太清楚什么错。它转换成数十六进制数,而是一个非常错误的。
I'm not too sure what's going wrong. It's converting the number into a hexadecimal number, but a very wrong one.
123.1443 gives 40000000
43.3 gives 60000000
8 gives 0
所以它做的事情,我只是不太清楚的东西。
so it's doing something, I'm just not too sure what.
帮助将AP preciated
Help would be appreciated
推荐答案
当你传递一个浮动
作为参数传递给一个可变参数函数(如的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类型
并传送到<$ C解决这个问题$ C>的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.
这篇关于转换IEEE 754浮点数与C十六进制 - 的printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!