How does Float.intBitsToFloat work?
Can anyone explain me or link some helpful resource in order to understand the algorithm behind the Java method Float.intBits开发者_开发百科ToFloat(int)
?
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:
#include <stdint.h>
union int_float_bits {
int32_t int_bits;
float float_bits;
};
float intBitsToFloat(int32_t x)
{
union int_float_bits bits;
bits.int_bits = x;
return bits.float_bits;
}
(Although technically this would be undefined behavior, in fact it virtually always works as expected.)
The JDK6 docs are quite good, and the source itself is pretty enlightening (it just uses a C union):
JNIEXPORT jfloat JNICALL
Java_java_lang_Float_intBitsToFloat(JNIEnv *env, jclass unused, jint v)
{
union {
int i;
float f;
} u;
u.i = (long)v;
return (jfloat)u.f;
}
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.
精彩评论