Float.intBitsToFloat 如何工作?
任何人都可以解释我或链接一些有用的资源,以便了解 Java 方法背后的算法 Float.intBitsToFloat(int)
?
Can anyone explain me or link some helpful resource in order to understand the algorithm behind the Java method Float.intBitsToFloat(int)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Java 使用 IEEE 754 浮点。
Float.intBitsToFloat(int)
的工作原理是解释其参数的 32 位,就好像它们以 此处描述。Double.longBitsToDouble(long)
对于 64 位浮点数的工作方式类似 如此处所述。在 C 中,您可能会达到如下所示的相同效果:(
尽管从技术上讲,这将是未定义的行为,但事实上它几乎总是按预期工作。)
Java uses IEEE 754 floating point.
Float.intBitsToFloat(int)
works by interpreting the 32 bits of its argument as if they specified a 32-bit float in the format described here.Double.longBitsToDouble(long)
works similarly for 64-bit floats as described here.In C you might achieve the same effect like so:
(Although technically this would be undefined behavior, in fact it virtually always works as expected.)
JDK6 文档非常好,并且源本身 非常有启发性(它只使用 C 联合):
The JDK6 docs are quite good, and the source itself is pretty enlightening (it just uses a C union):
在绝大多数现代平台上,CPU 上整数的默认大小是 32 位,浮点数的大小也是如此,因此我们假设两者之间的转换不会产生意外结果。您可能已经知道这一点,但在 Java 中整数不能声明为无符号,尽管您可以指定对应于 1 的十六进制值。正如 rlibby 和 Powers 先生所演示的,实际的转换是微不足道的,因为这些位只是解释不同。但是,该方法在您可能尝试处理二进制数据的多种情况下可能很有用。有一些有用的非标准技巧,例如此处描述的那些技巧,它们依赖于利用浮点数的 IEEE 754 表示法;也许在某个地方,当需要在位的整数和浮点表示之间进行转换时,可能会使用该方法。
On the vast majority of modern platforms, the default size of an integer on CPUs is 32 bits, as is the size of a float, so we'll assume that converting between the two yields no unexpected results. You probably already know this, but integers cannot be declared as unsigned in Java, though you can specify a hexadecimal value which corresponds to one. The actual conversion, as demonstrated by rlibby and Mr. Powers, is trivial, since the bits are just interpreted differently. However, the method may be useful in several scenarios where you may be trying to mess around with binary data. There are several useful nonstandard tricks, such as those described here, which rely on exploiting the IEEE 754 representation of a float; perhaps somewhere along the line, the method may come in use when the need to translate between integer and floating-point representations of bits arises.