我有一个无符号长整数值,它表示使用 IEEE-754 格式的浮点数。在 C++ 中将其打印为浮点数的最快方法是什么?
我知道一种方法,但我想知道 C++ 中是否有一个更好的方便实用程序。
我所知道的方式的例子是:
union
{
unsigned long ul;
float f;
} u;
u.ul = 1084227584; // in HEX, this is 0x40A00000
cout << "float value is: " << u.f << endl;
(这会打印出“float value is: 5”)
您建议的联合方法是大多数人通常会采取的路线。然而,从技术上来说未定义的行为在 C/C++ 中从联合中读取与最近写入的成员不同的成员。尽管如此,它在几乎所有编译器中都得到了很好的支持。
强制转换指针,如乔恩·斯基特建议 https://stackoverflow.com/questions/1856468/how-to-output-ieee-754-format-integer-as-a-float/1856476#1856476,是一个坏主意——这违反了严格别名 http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.htmlC 的规则。激进的优化编译器将为此生成不正确的代码,因为它假设类型的指针unsigned long *
and float *
永远不会互相别名。
就标准合规性而言(即不调用未定义的行为),最正确的方法是通过char*
,因为严格的别名规则允许char*
指向任何其他类型指针的别名的指针:
unsigned long ul = 0x40A00000;
float f;
char *pul = (char *)&ul; // ok, char* can alias any type
char *pf = (char *)&f; // ok, char* can alias any type
memcpy(pf, pul, sizeof(float));
老实说,我会选择联合方法。来自上面的 cellperformance.com 链接:
这是一种极其常见的习惯用法,并且受到所有主要编译器的良好支持。实际上,以任何顺序向工会的任何成员进行阅读和写作都是可以接受的做法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)