According to this answer, reading from any element of the union other than the last one written is either undefined behavior or implementation defined behavior depending on the version of the standard.
If you want to examine the binary representation of 3.14159f
, you can do so by casting the address of a float
and then dereferencing.
#include <stdint.h>
#include <stdio.h>
int main(){
float f = 3.14159f;
printf("%x\n", *(uint32_t*) &f);
}
The output of this program is 40490fd0
, which matches with the result given by this page.
As interjay correctly pointed out, the technique I present above violates the strict aliasing rule. To make the above code work correctly, one must pass the flag -fno-strict-aliasing
to gcc
or the equivalent flag to disable optimizations based on strict aliasing on other compilers.
Another way of viewing the bytes which does not violate strict aliasing and does not require the flag is using a char *
instead.
unsigned char* cp = (unsigned char*) &f;
printf("%02x%02x%02x%02x\n",cp[0],cp[1],cp[2],cp[3]);
Note that on little endian architectures such as x86, this will produce bytes in the opposite order as the first suggestion.