How to get float bit representation without UB in C++?

358 Views Asked by At

As far as I know, all 'traditional' ways of doing this, namely reinterpret_cast of a pointer and union with int and float fields are UB as violation of strict aliasing (in C++, not in C).
So, how to do it correctly without undefined behavior?

Can I do a reinterpret_cast to char * and memcpy that to uint32_t? Or maybestd::launder will help?

1

There are 1 best solutions below

9
On BEST ANSWER

The standard way to do it, as pointed out by Jason Turner, is to use memcpy:

float f = 1.0;
std::byte c[sizeof(f)];
memcpy(c, &f, sizeof(f));

You may be thinking that you do not want to copy anything, that you just want to see the bits/bytes. Well the compilers are smart and they will in fact optimize it away as demonstrated by Jason so do not worry and use memcpy for this kind of thing and never reinterpret_cast.