2

Does anyone know how to make a c equivalent to Java's Float.intBitsToFloat method?

https://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Float.html#intBitsToFloat(int)

I can't find any examples of it being ported.

Sam Hosseini
  • 813
  • 2
  • 9
  • 17
NJGUY
  • 2,045
  • 3
  • 23
  • 43
  • http://stackoverflow.com/questions/252552/why-do-we-need-c-unions – polarysekt Jun 03 '15 at 03:28
  • some other duplicates: [Building a 32bit float out of its 4 composite bytes](http://stackoverflow.com/q/3991478/995714) [Converting uint to float in C++](http://stackoverflow.com/q/5057428/995714) – phuclv Jun 03 '15 at 04:28

2 Answers2

1

This source has given a way to do this

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;
}    

So working around the above you can do something like this .

union int_to_float_bits {
    int32_t integer_bits;
    float converted_float_bits;
};

float intBitsToFloat(int32_t int_value)
{
    union int_to_float_bits bits;
    bits.integer_bits = int_value;
    return bits.converted_float_bits;
}
Ankur Anand
  • 3,873
  • 2
  • 23
  • 44
0

I like the idea Ankur has for this. Here is another way (a bit hackish mind you):

#include <stdio.h>

int main() {
  int v = 1090099610;
  float *f = (float*)(&v);
  printf("%E\n", *f);

  return 0;
}

Output: http://cpp.sh/6v2px

In jshell:

jshell> Float.intBitsToFloat(1090099610)
$1 ==> 7.8
smac89
  • 39,374
  • 15
  • 132
  • 179
  • `float *f = (float*)(&v);` is a [strict aliasing](https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule) violation. Also, if `&v` isn't properly aligned for a `float`, it's undefined behavior. – Andrew Henle May 17 '19 at 21:37