I need to store double
values in a file in a way that will be portable. I know I can just write them in human readable form like 1.23456789
, but I am hoping to save space by writing them as binary.
I know how to write binary to a file, but is there a way to do that in a way in which the resulting file will be the same regardless of the machine on which the code was compiled and executed? I am hoping to be able to read/write such files across machines in this way.
答案 0 :(得分:0)
You can always externalize the number according to IEEE 754. This is also the most used format in current CPUs, but if you want to be portable, you have to calculate the relevant fields (sign/exponent/fraction) in the required precision programmatically instead of directly using the in-memory representation of the current platform.
Another alternative is using fixed-point numbers. If the number range and precision you want to represent allows it, this might be the easier alternative.
答案 1 :(得分:0)
如果用于序列化double
值的计算机对double
值使用IEEE 754双精度,则可以分别存储符号,指数和尾数,以便使用在您要在其上加载任何其他系统上重建double值的信息:
typedef union _DI
{
double d;
uint64_t bits;
} DI;
DI foo;
uint64_t mask = 0x8000000000000000, sign, exp, mantissa, base;
int i;
foo.d = 3.141;
sign = !!(foo.bits & mask);
mask = 0x7FF0000000000000;
exp = ((foo.bits & mask) >> 52) - 1023;
mask = 0x000FFFFFFFFFFFFF;
mantissa = (foo.bits & mask);
请注意,尾数也必须为normalized。
答案 2 :(得分:0)
简单的答案是不。没有二进制可移植的方式以二进制形式编写浮点数。即使遵循IEEE-752文档,您也会发现可以按不同顺序存储符合浮点数的字节(例如整数的大/小尾数形式)
有几种IETF协议(最著名的IPFIX协议)定义了一种格式,用于将IEEE-752浮点数传输为所谓的网络格式。这迫使数字以从大到小的权重进行写入,但是例如,这迫使低字节序的机器(如intel的机器)在读取/写入导线时交换字节。
那么,人们在做什么?好吧,如果您想保存数据,则最好定义自己的格式,并在项目中始终遵循它。以一种独立于架构的方式。如果您很幸运,当其他人需要访问您的数据时,您可以告诉他们这些数据的存储方式,并且所有人都可以遵循您的规范,而不必成为必须适应它们的人。