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

4

1 回答 1

3

您需要知道哪些 4 字节的延伸是floats,哪些 4 字节的延伸是uints。如果你不知道,就没有办法转换它们,不幸的是,它们只是 32 位,含义不明确。但是,如果您确实知道第三个值是 a float,例如,您可以使用 获得它float v3 = ((float *)uint_pointer)[3]。此外,您可以查看我在上一篇文章中的冗长解释:iOS 6 中的 Granular Synthesis 使用 AudioFileServices

编辑:如果您不知道== sizeof(DWORD) == sizeof(float)包含您的值的是 4 个字节,并且作为一般的良好做法,您可以强制转换u*并从联合中访问它。这样,您可以使用编译器的内存对齐知识,因此v3 = ((u *)uint_pointer)[3].f更安全,请参阅@LightnessRacesInOrbit 的评论。

于 2013-01-17T01:43:24.877 回答