I'm receiving a buffer from a network which was converted to an array of 32-bit words. I have one word which is defined as an ieee float by my interface document. I need to extract this word from the buffer. It's tough to cast from one type to another without invoking a conversion. The bits are already adhere to the ieee float standard, I don't want to re-arrange any bits.
float ieee_float(uint32_t f)
{
return *((float*)((void*)(&f)));
}
In C++, the right way ™ is:
float ieee_float(uint32_t f)
{
static_assert(sizeof(float) == sizeof f, "`float` has a weird size.");
float ret;
std::memcpy(&ret, &f, sizeof(float));
return ret;
}
Both GCC and Clang at -O1
and above generate the same assembly for this code and a naive reinterpret_cast<float &>(f)
.
You have several options, as stated here :
union
solution: since C11 it is explicitly allowed (as said in the other answer). char
types can be aliased to any type. There's no C\/C++ language. They're different languages with different rules. The valid way in C is to use a union, but that's not allowed in C++. See
Even
reinterpret_cast<\/code> for type punning
In C++20 a new cast type called
std::bit_cast<\/code><\/a> was created exactly for this purpose
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.