1

I have an array which has data which is mixed in format. It contains both unsigned ints & floats (all stored in a 4 byte data each).

I want to convert each 4 byte data to a float. However, none of the methods worked for me. For example.

union
{
   DWORD i;
   float f;
} u; 

This method doesn't work. Neither does reinterpret_cast to float.

The data I have is like this.

{ 1, 8, 1.00000, -1.000000 }

I have a uint32_t pointer which points to the memory.

DWORD value = *(uint_pointer) gives me the 1, 8 correctly and not the others. Using a typecast float causes 1.00000 & -1.00000 to be recognized correctly but not the other two.

I basically want the result to be

{ 1.00000, 8.00000, 1.00000, -1.00000 }

I looked at SO for all the previous answers but none of them worked reliably hence I am posting this again to get some ideas.

Thanks

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
ssarangi
  • 602
  • 1
  • 10
  • 28

1 Answers1

3

You need to know which stretches of 4 bytes are floats and which stretches of 4 bytes are uints. If you don't know, there is no way to convert them, unfortunately, they are just 32 bits with ambiguous meaning. However, if you do know that the third value is a float, for example, you can obtain it with float v3 = ((float *)uint_pointer)[3]. Also, you could check out my lengthy explanation in this previous post: Granular Synthesis in iOS 6 using AudioFileServices

EDIT: If you don't know that it is 4 bytes == sizeof(DWORD) == sizeof(float) that contain your values, and as a good practice in general, you could cast to u* and access it from the union. That way, you use the compiler's knowledge of memory alignment, so v3 = ((u *)uint_pointer)[3].f is safer, see comment by @LightnessRacesInOrbit.

Community
  • 1
  • 1
s.bandara
  • 5,636
  • 1
  • 21
  • 36