Can I write a float as binary into a file and read it back on another computer, if both machines are x86 and use IEEE-754? Will it be exactly the same result, including sign, NAN, INF? Can I do that with double?
Asked
Active
Viewed 103 times
1
-
3Yes, you can do that. – Michael Aug 26 '18 at 18:25
-
2Even sign the sign and payload of the NaN are preserved – harold Aug 26 '18 at 18:27
-
3Yes, every normal C/C++ implementation on x86 uses the same object-representation for `double`, with the same float-endianness (little endian, same as integer). And within a program it's a trivially-copyable type. – Peter Cordes Aug 26 '18 at 18:30
-
1Whatr keeps you from using a trruely portable and easily debuggable text file format? – too honest for this site Aug 26 '18 at 18:45
-
1Define "safe". The **only** guarantee that the C and C++ language definitions give you with regard to binary files is that if you write data to a binary file you can read it back into a program compiled with the "same" compiler (where "same" implies that you have all the same compiler option settings). If "safe" means "will probably work with reasonable hardware and platform assumptions", then the answer may be "yes". – Pete Becker Aug 26 '18 at 18:56
-
@toohonestforthissite: presumably performance, and the inconvenience of restoring NaN payloads, and +/-0.0. little-endian IEEE754 `double` is not a bad choice for a data format, and you can `mmap` it directly from a file on many common ISAs. – Peter Cordes Aug 26 '18 at 21:31
-
@PeterCordes: No premature optimisations; maintainability is more important in the first place. Unfortunately OP is not interested in clarifying. There are safe ways to handle special values. Btw. those can also be problematic for binary formats; filtered writeing/reading is a good idea in general. Plus it is safer against unexpected modifications. IRL, sh** happens. – too honest for this site Aug 26 '18 at 22:20
-
1@toohonestforthissite: Why do you assume it's premature? It might be, it might not be. Sure it's worth pointing out that a text format might be appropriate, even at the cost of file-size and CPU usage. (And precision, unless you use a hex-float representation or something). But there are plenty of real-world formats that store big or little-endian IEEE binary32 or binary64, with appropriate metadata to indicate what format they're holding. – Peter Cordes Aug 26 '18 at 22:59