C/C++ - Convert 24-bit signed integer to float

前端 未结 7 2146
野的像风
野的像风 2021-01-12 20:27

I\'m programming in C++. I need to convert a 24-bit signed integer (stored in a 3-byte array) to float (normalizing to [-1.0,1.0]).

The platform is MSVC++ on x86 (wh

7条回答
  •  独厮守ぢ
    2021-01-12 20:45

    The solution that works for me:

    /**
     * Convert 24 byte that are saved into a char* and represent a float
     * in little endian format to a C float number.
     */
    float convert(const unsigned char* src)
    {
        float num_float;
        // concatenate the chars (short integers) and
        // save them to a long int
        long int num_integer = (
                ((src[2] & 0xFF) << 16) | 
                ((src[1] & 0xFF) << 8) | 
                (src[0] & 0xFF)
            ) & 0xFFFFFFFF;
    
        // copy the bits from the long int variable
        // to the float.
        memcpy(&num_float, &num_integer, 4);
    
        return num_float;
    }
    

提交回复
热议问题