Float16和Float32的互相转换

IEEE754规范

16位单精度

单精度二进制小数,使用32位存储。
1  5 10 位长
+-+--------+-----------------------+
|S| Exp | Fraction |
+-+--------+-----------------------+
15 14 10 9 0 位编号 (从右边开始为0)
偏正值 +15

32位单精度

单精度二进制小数,使用32位存储。
1 8 23 位长
+-+--------+-----------------------+
|S| Exp | Fraction |
+-+--------+-----------------------+
31 30 23 22 0 位编号 (从右边开始为0)
偏正值 +127

64位双精度

双精度二进制小数,使用64位存储。
1 11 52 位长
+-+--------+-----------------------+
|S| Exp | Fraction |
+-+--------+-----------------------+
63 62 52 51 0 位编号 (从右边开始为0)
偏正值 +1023

 

  /**
可以把16位的float IEEE754规范的int值转成32位的float

    */

 public static float halfFloatIntToFloat(int halfFloat) {
        int floatInt=((halfFloat & 0x8000) << 16) | (((((halfFloat >> 10) & 0x1f) - 15 + 127) & 0xff) << 23) | ((halfFloat & 0x03FF) << 13);
        return Float.intBitsToFloat(floatInt);
    }
    /**
可以把32的float值转化为IEEE754规范的int值

    */

 public static int floatToHalfFloatInt(float f) {
        int floatInt = Float.floatToIntBits(f);
        return ((floatInt >> 16) & 0x8000) | ((((floatInt >> 23) - 127 + 15) & 0x1f) << 10 )| ((floatInt >> 13) & 0x3ff);
    }

//把int值每八位转成一个字节,返回一个字节数组
 public static byte[] intToBytes(int value, int len) {
       
        byte[] b = new byte[len];
        for (int i = 0; i < len; i++) {
            b[len - i - 1] = (byte) ((value >> 8 * i) & 0xff);
        }
        return b;
    }
//把一个字节数组(每个字节代表一个int八位)转化成一个int数
    public static int bytesToInt(byte[] data, int startIndex, int len) {
      
        int sum = 0;
        int endIndex = startIndex + len;
        for (int i = startIndex; i < endIndex; i++) {
            int temp = ((int) data[i]) & 0xff;
            int moveBits = (--len) * 8;
            temp = temp << moveBits;
            sum += temp;
        }
        return sum;
    }

 

posted @ 2017-08-27 17:38  BlueBerry006  Views(5351)  Comments(0Edit  收藏  举报