Say I have a float I'd like to get the word value of:
float f = 42.0f; // 0xDEADBEEF
There are two options I know of.
std::cout << *(int*)&f;
This is undefined behavior, and I don't care to use a char*
as an exception (as shown here: dereferencing type-punned pointer will break strict-aliasing rules) since floats are 4 bytes and that would be messy.
union {
float f;
int i;
};
f = 42.0f;
std::cout << i;
This is also undefined behavior last time I checked, although this answer disagrees: What is the strict aliasing rule?
Is my only option to disable strict aliasing? I think there ought to be a way to get the underlying value (I'm computing a check sum if you're curious) without making such a large change.
User contributions licensed under CC BY-SA 3.0