Building a 32-bit float out of its 4 composite bytes

前端 未结 6 947
渐次进展
渐次进展 2020-11-27 05:10

I\'m trying to build a 32-bit float out of its 4 composite bytes. Is there a better (or more portable) way to do this than with the following method?

#includ         


        
6条回答
  •  广开言路
    2020-11-27 05:51

    You can use std::copy:

    float bytesToFloat(uchar b0, uchar b1, uchar b2, uchar b3) 
    { 
        uchar byte_array[] = { b3, b2, b1, b0 };
        float result;
        std::copy(reinterpret_cast(&byte_array[0]),
                  reinterpret_cast(&byte_array[4]),
                  reinterpret_cast(&result));
        return result;
    } 
    

    This avoids the union hack, which isn't technically allowed by the language. It also avoids the commonly used reinterpret_cast(byte_array), which violates the strict aliasing rules (it is permitted to reinterpret any object as an array of char, so the reinterpret_casts in this solution do not violate the strict aliasing rules).

    It still relies on float being four bytes in width and relies on your four bytes being a valid floating point number in your implementation's floating point format, but you either have to make those assumptions or you have to write special handling code to do the conversion.

提交回复
热议问题