C相当于Java的Float.intBitsToFloat

时间:2015-06-03 03:15:17

标签: java c

有谁知道如何使c等效于Java的Float.intBitsToFloat方法?

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

我找不到任何移植的例子。

2 个答案:

答案 0 :(得分:1)

source已经提供了一种方法

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

因此,解决上述问题,你可以做到这一点。

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

答案 1 :(得分:1)

我喜欢Ankur的想法。这是另一种方式(有点讨厌你):

#include <stdio.h>

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

  return 0;
}

输出:http://cpp.sh/6v2px

在jshell中:

jshell> Float.intBitsToFloat(1090099610)
$1 ==> 7.8
相关问题