Can anyone explain me or link some helpful resource in order to understand the algorithm behind the Java method Float.intBitsToFloat(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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With