/// <summary> /// Convert a 16-bit float (passed as a UInt16) to /// a float. The 16-bit float has a 9-bit mantissa, a 6-bit expontent /// and a sign bit. The format is similar to the IEEE-754 but in 16-bit /// form. The exponent uses a bias of 31 insead of 127. The mantissa /// is the upper 9-bits of a IEEE-754 32-bit float mantissa. /// </summary> /// <param name="float16">The float16 in and unsigned 16-bit format.</param> /// <returns>a 32-bit float.</returns> public static UInt16 float32ToFloat16(float value) { UInt32 float16 = 0; FloatUIntStruct fltIntVal = new FloatUIntStruct(); fltIntVal.floatValue = value; UInt32 mant = fltIntVal.uintValue & 0x007fffff; Int32 exp = (Int32)(fltIntVal.uintValue >> 23) & 0xff; if (exp == 0) //Max value { return(0); //Max value } exp -= 127; if (exp > 31) { return((UInt16)0x7E00); //Max positive value } else if (exp < -31) { return((UInt16)0xFE00); //Max negative value } else { mant = mant >> 14; exp = (exp + 31) & 0x3F; float16 = mant + (UInt32)(exp << 9); if ((fltIntVal.uintValue & 0x80000000) != 0) { float16 = float16 | 0x8000; } } return((UInt16)float16); }
/// <summary> /// Convert a 16-bit float (passed as a UInt16) to /// a float. The 16-bit float has a 9-bit mantissa, a 6-bit expontent /// and a sign bit. The format is similar to the IEEE-754 but in 16-bit /// form. The exponent uses a bias of 31 insead of 127. The mantissa /// is the upper 9-bits of a IEEE-754 32-bit float mantissa. /// </summary> /// <param name="float16">The float16 in and unsigned 16-bit format.</param> /// <returns>a 32-bit float.</returns> public static float float16ToFloat32(UInt16 float16) { FloatUIntStruct fltIntVal = new FloatUIntStruct(); fltIntVal.uintValue = 0; UInt32 mant = (UInt32)float16 & 0x01ff; Int32 exp = (Int32)((float16 & 0x7E00)) >> 9; if (exp == 0x2F) //Max value { fltIntVal.floatValue = (float)1.0e32; if ((float16 & 0x8000) != 0) { fltIntVal.uintValue |= 0x80000000; } return((float)1.0e32); //Max value } else if (exp == 0) { if (mant == 0) { fltIntVal.floatValue = (float)0.0; return(fltIntVal.floatValue); } else { //we are at our smallest 16-bit float value... //re-adjust mantissa and exp for 32-bit float; exp = -31; for (int i = 0; i < 9; ++i) { mant = mant << 1; --exp; if ((mant & 0x0200) != 0) { break; } } } } else { exp = exp - 31; //bias of 31. } mant = mant & 0x1FF; mant = mant << 14; //IEEE-754 mantisa exp = exp + 127; //IEEE-754 exp bias. fltIntVal.uintValue = ((UInt32)exp << 23) + mant; if ((float16 & 0x8000) != 0) { fltIntVal.uintValue |= 0x80000000; } return(fltIntVal.floatValue); }