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

前端 未结 6 932
渐次进展
渐次进展 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:42

    I typically use this in C -- no memcpy or union required. It may break aliasing rules in C++, I don't know.

    float bytesToFloat(uint8_t *bytes, bool big_endian) {
        float f;
        uint8_t *f_ptr = (uint8_t *) &f;
        if (big_endian) {
            f_ptr[3] = bytes[0];
            f_ptr[2] = bytes[1];
            f_ptr[1] = bytes[2];
            f_ptr[0] = bytes[3];
        } else {
            f_ptr[3] = bytes[3];
            f_ptr[2] = bytes[2];
            f_ptr[1] = bytes[1];
            f_ptr[0] = bytes[0];
        }
        return f;
    }
    

    If you have a whole array of bytes that need to be re-interpreted as floats, you can call the following procedure for each consecutive sequence of 4 bytes in the array if necessary, to switch the byte order (e.g. if you are running on a little endian machine, but the bytes are in big endian order). Then you can simply cast the uint8_t * array pointer to float *, and access the memory as an array of floats.

    void switchEndianness(uint8_t *bytes) {
        uint8_t b0 = bytes[0];
        uint8_t b1 = bytes[1];
        uint8_t b2 = bytes[2];
        uint8_t b3 = bytes[3];
        bytes[0] = b3;
        bytes[1] = b2;
        bytes[2] = b1;
        bytes[3] = b0;
    }
    

提交回复
热议问题