I’m writing software that has to work on different platforms. It uses floating point numbers. On all platforms, the floating point numbers have to be the same size in memory.
For integers I could use int32_t for example. How can I do this for floating point numbers?
If you need to force the values to the same size, you can design a representation that uses only integers of known sizes. You’d convert your floats to that format to save them, and you’d convert them back to floats when you read them.
See how can I extract the mantissa of a double for AProgrammer’s explanation of the
frexp()function, which will decompose a float into its (integer) exponent and a (double) mantissa. The comments following that answer will explain how to convert the mantissa to an integer.You can save the integer mantissa and exponent, which will have fixed lengths. Then you can read them back and use the
ldexp()function to re-create the original float (with some small error, of course).