Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.intBitsToFloat(int)?

like image 920
Archedius Avatar asked Dec 06 '22 22:12

Archedius


2 Answers

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

like image 200
rlibby Avatar answered Dec 10 '22 13:12

rlibby


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;
}    
like image 33
Bobby Powers Avatar answered Dec 10 '22 11:12

Bobby Powers