Data serialization in C?

前端 未结 5 1762
清歌不尽
清歌不尽 2021-01-14 20:50

I have this structure which I want to write to a file:

typedef struct
{
    char* egg;
    unsigned long sausage;
    long bacon;
    double spam;
} order;
<         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-14 21:16

    If you want to be as portable as possible with floats you can use frexp and ldexp:

    void WriteFloat (float number)
    {
      int exponent;
      unsigned long mantissa;
    
      mantissa = (unsigned int) (INT_MAX * frexp(number, &exponent);
    
      WriteInt (exponent);
      WriteUnsigned (mantissa);
    }
    
    float ReadFloat ()
    {
      int exponent = ReadInt();
      unsigned long mantissa = ReadUnsigned();
    
      float value = (float)mantissa / INT_MAX;
    
      return ldexp (value, exponent);
    }
    

    The Idea behind this is, that ldexp, frexp and INT_MAX are standard C. Also the precision of an unsigned long is usually at least as high as the width of the mantissa (no guarantee, but it is a valid assumption and I don't know a single architecture that is different here).

    Therefore the conversion works without precision loss. The division/multiplication with INT_MAX may loose a bit of precision during conversion, but that's a compromise one can live with.

提交回复
热议问题