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

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

    You could use a memcpy (Result)

    float f;
    uchar b[] = {b3, b2, b1, b0};
    memcpy(&f, &b, sizeof(f));
    return f;
    

    or a union* (Result)

    union {
      float f;
      uchar b[4];
    } u;
    u.b[3] = b0;
    u.b[2] = b1;
    u.b[1] = b2;
    u.b[0] = b3;
    return u.f;
    

    But this is no more portable than your code, since there is no guarantee that the platform is little-endian or the float is using IEEE binary32 or even sizeof(float) == 4.

    (Note*: As explained by @James, it is technically not allowed in the standard (C++ §[class.union]/1) to access the union member u.f.)

提交回复
热议问题