In his recent talk “Type punning in modern C++” Timur Doumler said that std::bit_cast
cannot be used to bit cast a float
into an unsigned char[4]
because C-style arrays cannot be returned from a function. We should either use std::memcpy
or wait until C++23 (or later) when something like reinterpret_cast<unsigned char*>(&f)[i]
will become well defined.
In C++20, can we use an std::array
with std::bit_cast
,
float f = /* some value */;
auto bits = std::bit_cast<std::array<unsigned char, sizeof(float)>>(f);
instead of a C-style array to get bytes of a float
?