Portable IEEE 754 Floating Point Reading and Writing

by Malcolm Mclean

IEEE 754 is the accepted standard for floating point arithmetic. However not all processors implement it, and there's not guarantee that future processors will implement it fully or exactly. So if you save a floating point number by simply dumping out the binary image with fwrite, there's a chance that your code will break.

These routines achieve the same thing, portably. It's quite tricky to get all the conditions right, and the bit packing and unpacking is logarithmic. However typically file access is so slow that it's not a noticeable bottleneck. You should drop these routines into you code every time you need to store or load a binary flating point number.

I've put in a flag for endianness, which means that you can achieve compatibility with raw binary writes on the vast majority of systems which use IEEE 754 internally. The code is written in pure, conservative ANSI C, if it breaks anywhere, let me know.

Source code

ieee754.h   ieee754.c