user826228
user826228

Reputation: 139

Storing a 32 bit float in a file portability concerns

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.

Upvotes: 2

Views: 1203

Answers (5)

Paul R
Paul R

Reputation: 212969

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.

Upvotes: 2

Ajay
Ajay

Reputation: 18411

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.

Upvotes: 0

gordy
gordy

Reputation: 9786

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

Upvotes: 0

Prime
Prime

Reputation: 4241

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.

Upvotes: 1

Mark B
Mark B

Reputation: 96241

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.

Upvotes: 6

Related Questions