C - Serialization of the floating point numbers (floats, doubles)

后端 未结 10 1063
攒了一身酷
攒了一身酷 2020-11-28 11:18

How to convert a floating point number into a sequence of bytes so that it can be persisted in a file? Such algorithm must be fast and highly portable. It must allow also th

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 12:03

    This version has excess of only one byte per one floating point value to indicate the endianness. But I think, it is still not very portable however.

    #include 
    #include 
    #include 
    #include 
    
    #define LITEND      'L'
    #define BIGEND      'B'
    
    typedef short               INT16;
    typedef int                 INT32;
    typedef double              vec1_t;
    
     typedef struct {
        FILE            *fp;
    } WFILE, RFILE;
    
    #define w_byte(c, p)    putc((c), (p)->fp)
    #define r_byte(p)       getc((p)->fp)
    
    static void w_vec1(vec1_t v1_Val, WFILE *p)
    {
        INT32   i;
        char    *pc_Val;
    
        pc_Val = (char *)&v1_Val;
    
        w_byte(LITEND, p);
        for (i = 0; ifp = fopen("test.bin", "w");
        v1_Val = 1234567890.0987654321;
        printf("v1_Val before write = %.20f \n", v1_Val);
        w_vec1(v1_Val, px_FileW);
        fclose(px_FileW->fp);
    
        px_FileR->fp = fopen("test.bin", "r");
        v1_Val = r_vec1(px_FileR);
        printf("v1_Val after read = %.20f \n", v1_Val);
        fclose(px_FileR->fp);
        return 0;
    }
    

提交回复
热议问题