Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output IEEE-754 format integer as a float

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++?

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

Example of the way that I know is:

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

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

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

(This prints out "float value is: 5" )

like image 529
Tom Avatar asked Dec 04 '22 14:12

Tom


2 Answers

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.

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.

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));

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.

like image 98
Adam Rosenfield Avatar answered Dec 06 '22 02:12

Adam Rosenfield


It will only work on 32-bit machines or machines where sizeof(long) == sizeof(float). On modern machines you might want to use int instead ... and you really have to take care if you're performing this trick.

like image 37
arhuaco Avatar answered Dec 06 '22 03:12

arhuaco