Serialize double and float with C

后端 未结 8 1270
孤街浪徒
孤街浪徒 2020-12-01 09:47

How can I serialize doubles and floats in C?

I have the following code for serializing shorts, ints, and chars.

unsigned char * serialize_char(unsign         


        
8条回答
  •  忘掉有多难
    2020-12-01 10:32

    This packs a floating point value into an int and long long pair, which you can then serialise with your other functions. The unpack() function is used to deserialise.

    The pair of numbers represent the exponent and fractional part of the number respectively.

    #define FRAC_MAX 9223372036854775807LL /* 2**63 - 1 */
    
    struct dbl_packed
    {
        int exp;
        long long frac;
    };
    
    void pack(double x, struct dbl_packed *r)
    {
        double xf = fabs(frexp(x, &r->exp)) - 0.5;
    
        if (xf < 0.0)
        {
            r->frac = 0;
            return;
        }
    
        r->frac = 1 + (long long)(xf * 2.0 * (FRAC_MAX - 1));
    
        if (x < 0.0)
            r->frac = -r->frac;
    }
    
    double unpack(const struct dbl_packed *p)
    {
        double xf, x;
    
        if (p->frac == 0)
            return 0.0;
    
        xf = ((double)(llabs(p->frac) - 1) / (FRAC_MAX - 1)) / 2.0;
    
        x = ldexp(xf + 0.5, p->exp);
    
        if (p->frac < 0)
            x = -x;
    
        return x;
    }
    

提交回复
热议问题