开发者

How to make sure the size of a floating point is the same across platforms?

开发者 https://www.devze.com 2023-04-07 01:09 出处:网络
I\'m writing software that has to work on different platforms. It uses floating point numbers. On all platfo开发者_如何学Gorms, the floating point numbers have to be the same size in memory.

I'm writing software that has to work on different platforms. It uses floating point numbers. On all platfo开发者_如何学Gorms, 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).


You can't do it portably in C; you have to take what the systems provide.

That said, on all systems I know of, sizeof(float) == 4 and sizeof(double) == 8, but relying on that absolutely is dangerous.

Different machines can store the same value differently. They might use different floating-point formats, or they might all use IEEE 754. Even if they all use IEEE 754, they might store them in big-endian or little-endian order.

You must decide why you think they must all be the same size. The chances are, you are trying to take some unwarranted short cuts in relaying information between different machines. Don't take the short cuts; they will lead you into problems at some point. If you feel you must, you have to assess what your portability goals really are, and validate whether you can meet them with the design you're proposing. But be very cautious!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号