How to output IEEE-754 format integer as float

I have an unsigned integer that is a float using the IEEE-754 format. What is the fastest way to print it as a float in C ++?

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

An example of how I know:

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

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

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

(This means that the value is "float value: 5")

+3
source share
5 answers

- , . , undefined C/++ , , . , , .

, Jon Skeet, , C. , , unsigned long * float * .

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

, union. cellperformance.com :

. , .

+6

EDIT: , " ", , - . . , , ( !)


:

long ul = 1084227584;
float* fp = (float*) &ul;
float f = *fp;

( , , ).

, ... , .

, , , .

+3

32- , sizeof (long) == sizeof (float). int ... , .

+3
source

I was thinking the same thing as John Skeet, but he beat me. However, I would do it a little more briefly than he.

cout << "float value is: " << *((float *) &ulValue)) << endl;

You get a pointer to your unsigned long, and then reinterpret it as a pointer to a float, and then dereferencing your pointer to a float, returns a float value.

Since you are doing this in C ++, it is better to use reinterpret_cast instead of the old C-style.

cout << "float value is: " << *(reinterpret_cast<float *>(&ulValue)) << endl;
+3
source

swegi had the right direction, but missed one character. The right way -

long l = 1084227584L
float f = reinterpret_cast<float&>(l);
+1
source

Source: https://habr.com/ru/post/1724878/


All Articles