在文件中存储32位浮点可移植性问题 [英] Storing a 32 bit float in a file portability concerns

查看:121
本文介绍了在文件中存储32位浮点可移植性问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I store a float in a file via this code

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

使用此代码读取文件的程序会导致运行时错误的频率,因为float为8个字节of 4?

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;

我可以总是读取4个字节并将其转换为8字节浮点数吗?

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

强调不同的Windows平台64位和32位。

Emphasis on different Windows Platforms 64 bit vs 32 bit.

推荐答案

我不太担心浮动的大小,更担心它的字节顺序。我想说绝大多数的C ++实现使用IEEE 754,这意味着float总是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.

这篇关于在文件中存储32位浮点可移植性问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆