user2191981
user2191981

Reputation: 21

Reinterpreting an unsigned int to a float in C++

I have a float representation stored in an unsigned __int32. I know that you can reconstruct the number byte shifting, just as instructed in the answer of this question:

Convert int to float in C (no casting)

I want to avoid the shifting, multiplications and sums and just reinterpret the bits. I tried the Wikipedia example for IEEE 754 single precision entry but the reinterpretation results in a 0.

Here's my code:

unsigned __int32 integer = 0;   
unsigned __int32 mask = 0;
mask = mask + 1 << 30;
mask = mask + 1 << 29;
mask = mask + 1 << 28;
mask = mask + 1 << 27;
mask = mask + 1 << 26;
mask = mask + 1 << 22;
integer = integer ^ mask;
printf("%ld %d\n", integer, sizeof(__int32));
float* decimal = reinterpret_cast<float*>(&integer);
printf("%f", *decimal);
return 0;

Upvotes: 1

Views: 3233

Answers (1)

Mark B
Mark B

Reputation: 96233

Most likely the problem here is that you're violating the strict alias rules by having two differently typed (non-char) pointers point to the same memory location.

The simplest, most straightforward solution to your problem is just to memcpy the bytes (after asserting that the size of your integer and float types are the same):

float decimal = 0.0f;
memcpy(&decimal, &integer, sizeof(integer));

Upvotes: 3

Related Questions