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

后端 未结 9 2220
余生分开走
余生分开走 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:31

    What's wrong with a human readable format.

    It has a couple of advantages over binary:

    • It's readable
    • It's portable
    • It makes support really easy
      (as you can ask the user to look at it in their favorite editor even word)
    • It's easy to fix
      (or adjust files manually in error situations)

    Disadvantage:

    • It's not compact
      If this a real problem you can always zip it.
    • It may be slightly slower to extract/generate
      Note a binary format probably needs to be normalized as well (see htonl())

    To output a double at full precision:

    double v = 2.20;
    std::cout << std::setprecision(std::numeric_limits::digits) << v;
    

    OK. I am not convinced that is exactly precise. It may lose precision.

提交回复
热议问题