简体   繁体   English

如何将double转换为char []并返回以读取/写入二进制文件?

[英]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. 我试图将双精度型写入二进制文件,但无法弄清楚如何以可移植的方式将其转换为char []。 I'd like to write it in the IEEE double precision format , big endian, and convert it back to the current platform's format. 我想以IEEE双精度格式 big endian编写它,并将其转换回当前平台的格式。

Thanks for the help. 谢谢您的帮助。

Various approaches: 各种方法:

1) Use a string. 1)使用字符串。 If FLT_RADIX is 10, use fprintf(outf, " %.*e", DBL_DECIMAL_DIG-1, x) , otherwise use fprintf(outf, " %a", x) ( Ref ). 如果FLT_RADIX为10,请使用fprintf(outf, " %.*e", DBL_DECIMAL_DIG-1, x) ,否则请使用fprintf(outf, " %a", x)Ref )。 Use fscanf(inf, "%lf", &x) to read back. 使用fscanf(inf, "%lf", &x)进行回读。 ( "%la" has same effect) "%la"具有相同的作用)

2) Use a union and assume double format is IEEE double precision binary format , maybe also use defined endian and *nix: htonl() 2)使用联合并假定double格式是IEEE double precision二进制格式 ,也可以使用定义的endian和* 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. 3)考虑到不同的精度,范围, 摆动精度 ,+ /-0, 次法线等,向IEEE秘密编译器的非标准double编写大量代码。

Recommend option 1 推荐选项1

C和C ++具有fread和fwrite,它们只需将指定位置的字节以指定的块大小复制到指定的文件流,反之亦然...您不必转换为char []

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM