by markrages · 11y ago · 0 comments
This document says this is a GCC-specific extension. Is this true? Or is it one of those things that's not standardized, but the compiler vendors all do it anyway?
Type punning by union is implementation defined behavior. Everyone fortunately defines it to Do The Right Thing (TM).
The truly standard supported way to type pun is by memcpy
float f = ...; int x; memcpy(&x, &f, sizeof x);
char bytes[5] = {0};
float flt = *(float*)&(bytes[1]);
Using memcpy works on any platform with 4 byte floats: char bytes[5] = {0};
float flt;
memcpy(&flt, &(bytes[1]), 4);Embedded targets are always memory-constrained. If they aren't, you are wasting money on hardware.
[0] see "ISO/IEC 9899:1999 Technical Corrigendum 3", http://www.open-std.org/Jtc1/sc22/wg14/www/docs/n1235.pdf