Java Float to floatToHalf(float f)

Here you can find the source of floatToHalf(float f)

Description

float To Half

License

Open Source License

Declaration

public static final int floatToHalf(float f) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static final int floatToHalf(float f) {
        int i = Float.floatToRawIntBits(f);
        // unpack the s, e and m of the float
        int s = (i >> 16) & 0x00008000;
        int e = ((i >> 23) & 0x000000ff) - (127 - 15);
        int m = i & 0x007fffff;
        // pack them back up, forming a half
        if (e <= 0) {
            if (e < -10) {
                // E is less than -10. The absolute value of f is less than
                // HALF_MIN
                // convert f to 0
                return 0;
            }//from  w w w.  ja v  a2s  .co m
            // E is between -10 and 0.
            m = (m | 0x00800000) >> (1 - e);
            // Round to nearest, round "0.5" up.
            if ((m & 0x00001000) == 0x00001000)
                m += 0x00002000;
            // Assemble the half from s, e (zero) and m.
            return s | (m >> 13);
        } else if (e == 0xff - (127 - 15)) {
            if (m == 0) {
                // F is an infinity; convert f to a half infinity
                return s | 0x7c00;
            } else {
                // F is a NAN; we produce a half NAN that preserves the sign bit
                // and the 10 leftmost bits of the significand of f
                m >>= 13;
                return s | 0x7c00 | m | ((m == 0) ? 0 : 1);
            }
        } else {
            // E is greater than zero. F is a normalized float. Round to
            // nearest, round "0.5" up
            if ((m & 0x00001000) == 0x00001000) {
                m += 0x00002000;
                if ((m & 0x00800000) == 0x00800000) {
                    m = 0;
                    e += 1;
                }
            }
            // Handle exponent overflow
            if (e > 30) {
                // overflow (); // Cause a hardware floating point overflow;
                return s | 0x7c00; // if this returns, the half becomes an
            } // infinity with the same sign as f.
              // Assemble the half from s, e and m.
            return s | (e << 10) | (m >> 13);
        }
    }
}

Related

  1. floatToBasicType(float f, Class clazz)
  2. floatToBinaryStringUnsigned(float value)
  3. floatToChar(float[] values)
  4. FloatToInt(double x)
  5. floatToIntColor(float value)
  6. floatToPrefixCoded(float val)
  7. floatToRegisters(float f)