How to convert a floating point number into a sequence of bytes so that it can be persisted in a file? Such algorithm must be fast and highly portable. It must allow also the opposite operation, deserialization. It would be nice if only very tiny excess of bits per value (persistent space) is required.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
Here we go.
Portable IEEE 754 serialisation / deserialisation that should work regardless of the machine's internal floating point representation.
https://github.com/MalcolmMcLean/ieee754
This version has excess of only one byte per one floating point value to indicate the endianness. But I think, it is still not very portable however.
This might give you a good start - it packs a floating point value into an
int
andlong long
pair, which you can then serialise in the usual way.What do you mean, "portable"?
For portability, remember to keep the numbers within the limits defined in the Standard: use a single number outside these limits, and there goes all portability down the drain.
5.2.4.2.2 Characteristics of floating types <float.h>
Note the implementation-defined in all these clauses.
What level of portability do you require? If the file is to be read on a computer with the same OS that it was generated on, than you using a binary file and just saving and restoring the bit pattern should work. Otherwise as boytheo said, ASCII is your friend.
sprintf, fprintf ? you don't get any more portable than that.