Read word value (hex) of float


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.

  1. Type-pun with
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.

  1. Use a union
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.

asked on Stack Overflow Mar 29, 2020 by MalumProhibitum

0 Answers

Nobody has answered this question yet.

User contributions licensed under CC BY-SA 3.0