How does Float.intBitsToFloat work?

Can someone explain to me or link a useful resource to understand the algorithm underlying the Java method Float.intBitsToFloat(int) ?

+4
source share
3 answers

Java uses the 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 can achieve the same effect:

 #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 will be undefined behavior, it actually almost always works as expected.)

+6
source

JDK6 docs are pretty good, and the source itself is pretty interesting (it just uses C):

 JNIEXPORT jfloat JNICALL Java_java_lang_Float_intBitsToFloat(JNIEnv *env, jclass unused, jint v) { union { int i; float f; } u; ui = (long)v; return (jfloat)uf; } 
+5
source

On the vast majority of modern platforms, the default size for the CPU is 32 bits by default, as well as the size of the float, so we assume that the conversion between the two results does not lead to unexpected results. You probably already know this, but integers cannot be declared unsigned in Java, although you can specify a hexadecimal value corresponding to one. The actual conversion, as demonstrated by rlibby and Mr. Powers, is trivial, since the bit is simply interpreted differently. However, this method can be useful in several scenarios where you can try to combine with binary data. There are several useful custom tricks, such as those described here , that are based on using the IEEE 754 float view; perhaps somewhere along the line, this method can be used when it becomes necessary to translate between integer and floating representations of bits.

+2
source

Source: https://habr.com/ru/post/1347854/


All Articles