如何以浮点形式输出IEEE-754格式整数 [英] How to output IEEE-754 format integer as a float

查看:144
本文介绍了如何以浮点形式输出IEEE-754格式整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无符号的长整数值,它表示使用IEEE-754格式的浮点数。什么是在C ++中以浮点形式将其打印出来的最快方法是什么?

I have a unsigned long integer value which represents a float using IEEE-754 format. What is the quickest way of printing it out as a float in C++?

我知道一种方法,但是我想知道C ++中是否有方便的实用程序会更好?

I know one way, but am wondering if there is a convenient utility in C++ that would be better.

我知道的方式示例是:

union
{
    unsigned long ul;
    float f;
} u;

u.ul = 1084227584; // in HEX, this is 0x40A00000

cout << "float value is: " << u.f << endl;

(打印出浮点值为5)

推荐答案

您建议的并集方法是大多数人会采用的通常方法。但是,从技术上讲,C / C ++中的未定义行为是从联合中读取与最近编写的成员不同的成员。尽管如此,它还是在所有编译器中得到了很好的支持。

The union method you suggested is the usual route that most people would take. However, it's technically undefined behavior in C/C++ to read a different member from a union than the one that was most recently written. Despite this, though, it's well-supported among pretty much all compilers.

投射指针,如 Jon Skeet建议,这是个坏主意-违反了严格别名C的规则。积极的优化编译器会为此生成错误的代码,因为它假设类型为 unsigned long * float * 的指针永远不会相互别名。

Casting pointers, as Jon Skeet suggested, is a bad idea -- that violates the strict aliasing rules of C. An aggressive optimizing compiler will produce incorrect code for this, since it assumes that pointers of types unsigned long * and float * will never alias each other.

就标准合规性(即不调用未定义行为)而言,最正确的方法是通过 char * ,因为严格的别名规则允许 char * 指针别名任何其他类型的指针:

The most correct way, in terms of standards compliance (that is, not invoking undefined behavior), is to cast through a char*, since the strict aliasing rules permit a char* pointer to alias a pointer of any other type:

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链接:

Though honestly, I would just go with the union method. From the cellperformance.com link above:


这是一个非常常见的习惯用法,并且得到所有主要编译器的良好支持。实际上,以任何顺序对工会的任何成员进行读写都是可接受的做法。

It is an extremely common idiom and is well-supported by all major compilers. As a practical matter, reading and writing to any member of a union, in any order, is acceptable practice.

这篇关于如何以浮点形式输出IEEE-754格式整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆