1

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;
Community
  • 1
  • 1
user2191981
  • 21
  • 1
  • 4
  • 3
    Try printing out the `mask` to verify it is what you expect it to be, and then read about [operator precedence](http://en.cppreference.com/w/cpp/language/operator_precedence). – Praetorian Mar 20 '13 at 18:00
  • That looks roughly how I would try to do what you say. What CPU are you working against here? Various assemblers do this in different ways (store int; load float; convert direct; etc.) Looking at the assembler output here in a debugger should give you a clue on what is going wrong here. – Michael Dorgan Mar 20 '13 at 18:02
  • Ah, use parenthesis or mask all you bits at once is what @Praetorian is wisely suggesting. :) – Michael Dorgan Mar 20 '13 at 18:03
  • Reinterpreting the bits is exactly what your `reinterpret_cast` is doing. I'm confused as to what it is you actually want to achieve. –  Mar 20 '13 at 18:07
  • 2
    btw, you can do `float decimal = reinterpret_cast(integer);` --- no need for pointers. – Walter Mar 20 '13 at 18:17
  • Thanks for pointing out @Pretorian, not the main issue, but certaintly it was also wrong. – user2191981 Mar 20 '13 at 20:42

1 Answers1

3

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));
Mark B
  • 95,107
  • 10
  • 109
  • 188