Search code examples
cbinaryfilesieee-754

How to convert a double to a char[] and back for reading / writing to binary file?


I'm trying to write a double to a binary file, but can't figure out how to convert it to a char[] in a portable way. I'd like to write it in the IEEE double precision format, big endian, and convert it back to the current platform's format.

Thanks for the help.


Solution

  • Various approaches:

    1) Use a string. If FLT_RADIX is 10, use fprintf(outf, " %.*e", DBL_DECIMAL_DIG-1, x), otherwise use fprintf(outf, " %a", x) (Ref). Use fscanf(inf, "%lf", &x) to read back. ("%la" has same effect)

    2) Use a union and assume double format is IEEE double precision binary format, maybe also use defined endian and *nix: htonl()

    union d2a {
      double d;
      unsigned char uc[sizeof double];
    } u;
    
    u.d = x;
    ToNetworkEndian(u.uc);
    fwrite(u.uc, 1, sizeof u.uc, outf);
    
    fread(u.uc, 1, sizeof u.uc, inf);
    FromNetworkEndian(u.uc);
    x = u.d;
    

    3) Write a lot of code to covert compiler's non-standard double to IEEE taking into account: different precision, range, wobbling precision, +/- 0, sub-normals, etc.

    Recommend option 1