简体   繁体   中英

intBitsToFloat counterpart: floatToIntBits or floatToRawIntBits?

In a very specific task, I am forced to store a float in an int variable (which will be persisted later, and then read back). All operations are done as float , ie a possible scenario is as follows:

  1. Calculate the float value, and work with it
  2. Store it as an int
  3. Later, read the int , and convert it to float immediately
  4. Work with the float value again

That is, int is purely a storage format. I was thinking of using intBitsToFloat to regain my float value. In this case, which is the proper method for exporting the float value? floatToIntBits() or floatToRawIntBits() ? I can't find it in the javadoc or anywhere else.

Actually the difference in these two methods is well described in Float API, these methods produce different results only for NaN but both results are valid and for your task you can use any of them. NaN may have many representations s111 1111 1axx xxxx xxxx xxxx xxxx xxxx , see http://en.wikipedia.org/wiki/NaN . floatToIntBits always returns 0111 1111 1100 0000 0000 0000 0000 0000 for NaN while floatToInt returns NaN binary representation as is.

I managed to find it in the Android source code. The appropriate counterpart of intBitsToFloat() is floatToRawIntBits() . Their C source code is as follows:

static jint floatToRawBits(JNIEnv* env, jclass clazz, jfloat val)
{
    Float   f;
    f.f = val;
    return f.bits;
}

static jfloat intBitsToFloat(JNIEnv* env, jclass clazz, jint val)
{
    Float   f;
    f.bits = val;
    return f.f;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM