简体   繁体   中英

bitwise casting uint32_t to float in C/C++

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 :

  • Use the union solution: since C11 it is explicitly allowed (as said in the other answer).
  • Instead of using an array of 32 bit words, use an array of 8 bit words (uint8_t), since 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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM