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

前端 未结 6 940
渐次进展
渐次进展 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 06:01

    If you want a portable way to do this, you'll have to write a bit of code to detect the endianess of the system.

    float bytesToFloatA(uchar b0, uchar b1, uchar b2, uchar b3)
    {
        float output;
    
        *((uchar*)(&output) + 3) = b0;
        *((uchar*)(&output) + 2) = b1;
        *((uchar*)(&output) + 1) = b2;
        *((uchar*)(&output) + 0) = b3;
    
        return output;
    }
    
    
    float bytesToFloatB(uchar b0, uchar b1, uchar b2, uchar b3)
    {
        float output;
    
        *((uchar*)(&output) + 3) = b3;
        *((uchar*)(&output) + 2) = b2;
        *((uchar*)(&output) + 1) = b1;
        *((uchar*)(&output) + 0) = b0;
    
        return output;
    }
    
    float (*correctFunction)(uchar b0, uchar b1, uchar b2, uchar b3) = bytesToFloatA;
    
    if ((*correctFunction)(0x3e, 0xaa, 0xaa, 0xab) != 1.f/3.f) // horrifying, I know
    {
      correctFunction = bytesToFloatB;
    }
    

提交回复
热议问题