Portability of binary serialization of double/float type in C++

后端 未结 9 2213
余生分开走
余生分开走 2020-11-27 15:50

The C++ standard does not discuss the underlying layout of float and double types, only the range of values they should represent. (This is also true for signed types, is i

9条回答
  •  醉话见心
    2020-11-27 16:25

    Take a look at the (old) gtypes.h file implementation in glib 2 - it includes the following:

    #if G_BYTE_ORDER == G_LITTLE_ENDIAN
    union _GFloatIEEE754
    {
      gfloat v_float;
      struct {
        guint mantissa : 23;
        guint biased_exponent : 8;
        guint sign : 1;
      } mpn;
    };
    union _GDoubleIEEE754
    {
      gdouble v_double;
      struct {
        guint mantissa_low : 32;
        guint mantissa_high : 20;
        guint biased_exponent : 11;
        guint sign : 1;
      } mpn;
    };
    #elif G_BYTE_ORDER == G_BIG_ENDIAN
    union _GFloatIEEE754
    {
      gfloat v_float;
      struct {
        guint sign : 1;
        guint biased_exponent : 8;
        guint mantissa : 23;
      } mpn;
    };
    union _GDoubleIEEE754
    {
      gdouble v_double;
      struct {
        guint sign : 1;
        guint biased_exponent : 11;
        guint mantissa_high : 20;
        guint mantissa_low : 32;
      } mpn;
    };
    #else /* !G_LITTLE_ENDIAN && !G_BIG_ENDIAN */
    #error unknown ENDIAN type
    #endif /* !G_LITTLE_ENDIAN && !G_BIG_ENDIAN */
    

    glib link

提交回复
热议问题