在文件中存储 32 位浮点数可移植性问题

发布于 2024-11-24 01:55:54 字数 340 浏览 4 评论 0原文

如果我通过此代码将浮点数存储在文件中,则

fwrite((void*)(&v), sizeof(v), 1, f); // v is a float.

使用此代码读取文件的程序会多久导致一次运行时错误,因为浮点数是 8 个字节而不是 4 个字节?

float v;
fread((void*)(&v), sizeof(v), 1, f);
return v;

我是否可以始终读取 4 个字节并将其转换为 8 字节浮点数?这样会更便携吗?

重点关注不同的 Windows 平台 64 位与 32 位。

If I store a float in a file via this code

fwrite((void*)(&v), sizeof(v), 1, f); // v is a float.

how often will a program reading the file with this code cause a runtime error because float is 8 bytes instead of 4?

float v;
fread((void*)(&v), sizeof(v), 1, f);
return v;

Can I always read 4 bytes and cast that to an 8 byte float? Would that be more portable?

Emphasis on different Windows Platforms 64 bit vs 32 bit.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

冷心人i 2024-12-01 01:55:54

我不太担心浮点数的大小,而更担心它的字节顺序。我想说绝大多数 C++ 实现都使用 IEEE 754,这意味着浮点总是 32 位和双精度 64 位。

您可能希望仅序列化该值的文本表示形式,或者特别注意确保字节顺序正确。

I would be less worried about the size of the float and more worried about the endianness of it. I'd say the vast majority of C++ implementation use IEEE 754 which would mean float is always going to be 32 bits and double 64 bits.

You may wish to just serialize a text representation of the value, or else take particular care to make sure that the byte order is correct.

酒儿 2024-12-01 01:55:54

如果可以的话,将数据存储为文本而不是原始二进制文件总是更好。这避免了上述问题和无数其他问题,例如:

  • 、浮点
  • 字节序、元素大小
  • 等的不同格式、
  • 填充/对齐、
  • 不同程序版本之间的前向/后向兼容性

。如果需要,它还使数据可供其他程序使用。

当然,缺点是文本需要更多存储空间,因此如果您有大量数据,那么文本可能不是一个选择。

It's always better to store data as text rather than raw binary if you reasonably can. This avoids the above problem and a myriad other issues such as:

  • endianness
  • element sizes
  • differing formats for float et al
  • padding/alignment
  • forward/backward compatibility between different program versions

It also makes the data usable by other programs if needed.

The down-side of course is that text requires more storage, so if you have a lot of data then text may not be an option.

恏ㄋ傷疤忘ㄋ疼 2024-12-01 01:55:54

float 的大小可能会改变,但 double 不会。您确定为此目的使用 double 不是更好的主意吗? double 始终为 8 个字节。

The size of float might change, but double does not. Are you sure it wouldn't be a better idea to use a double then for that purpose? A double is always 8 bytes.

征棹 2024-12-01 01:55:54

float 在引用 IEEE 单精度浮点时非常通用,无论平台是 32 位还是 64 位。

float pretty universal in referring to an IEEE single precision float, regardless if the platform is 32bit or 64bit.

迷雾森÷林ヴ 2024-12-01 01:55:54

在 Windows 平台上,无论是 32 位还是 64 位进程/操作系统,sizeof(float) 始终为 4 个字节。不知道标准,但在大多数平台上,浮点数的大小是四个字节。

On Windows platform, sizeof(float) is always 4 bytes irrespective if it is 32-bit or 64-bit process/OS. Don't know about standard, but on most platforms, sizeof a float is four bytes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文