如何确保跨平台浮点数的大小相同?

发布于 2024-12-06 11:34:27 字数 114 浏览 0 评论 0原文

我正在编写必须在不同平台上运行的软件。它使用浮点数。在所有平台上,浮点数在内存中的大小必须相同。

例如,对于整数,我可以使用 int32_t 。我该如何对浮点数执行此操作?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

终弃我 2024-12-13 11:34:27

如果您需要强制这些值具有相同的大小,您可以设计一种仅使用已知大小的整数的表示形式。您可以将浮点数转换为该格式以保存它们,并且在读取它们时将它们转换回浮点数。

请参阅如何提取双精度数的尾数 AProgrammer 对 frexp() 函数的解释,该函数将浮点数分解为其(整数)指数和(双精度)尾数。该答案后面的注释将解释如何将尾数转换为整数。

您可以保存整数尾数和指数,它们的长度固定。然后您可以读回它们并使用 ldexp() 函数重新创建原始浮点数(当然,会有一些小错误)。

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).

星軌x 2024-12-13 11:34:27

你不能在 C 中移植它;你必须接受系统提供的东西。

也就是说,在我知道的所有系统上,sizeof(float) == 4sizeof(double) == 8,但依赖它绝对是危险的。

不同的机器可以以不同的方式存储相同的值。它们可能使用不同的浮点格式,也可能全部使用 IEEE 754。即使它们全部使用 IEEE 754,它们也可能以大端或小端顺序存储。

您必须决定为什么您认为它们必须具有相同的大小。很可能,您试图在不同机器之间传递信息时采取一些无根据的捷径。不要走捷径;它们会在某个时候让你陷入问题。如果您认为必须这样做,则必须评估您的可移植性目标的真正含义,并验证您是否可以通过所提议的设计来满足这些目标。但要非常小心!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文