Storing a 32 bit float in a file portability concerns

霸气de小男生 提交于 2020-01-15 05:08:27

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/6715545/storing-a-32-bit-float-in-a-file-portability-concerns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!