在文件中存储 32 位浮点数可移植性问题
如果我通过此代码将浮点数存储在文件中,则
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不太担心浮点数的大小,而更担心它的字节顺序。我想说绝大多数 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.
如果可以的话,将数据存储为文本而不是原始二进制文件总是更好。这避免了上述问题和无数其他问题,例如:
。如果需要,它还使数据可供其他程序使用。
当然,缺点是文本需要更多存储空间,因此如果您有大量数据,那么文本可能不是一个选择。
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:
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.
float
的大小可能会改变,但double
不会。您确定为此目的使用 double 不是更好的主意吗?double
始终为 8 个字节。The size of
float
might change, butdouble
does not. Are you sure it wouldn't be a better idea to use adouble
then for that purpose? Adouble
is always 8 bytes.float 在引用 IEEE 单精度浮点时非常通用,无论平台是 32 位还是 64 位。
float pretty universal in referring to an IEEE single precision float, regardless if the platform is 32bit or 64bit.
在 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.