将字节数组转换为16位浮点数 [英] convert byte array to 16 bits float
本文介绍了将字节数组转换为16位浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个2字节的网络数组,需要将其转换为浮点
[值介于-1 ... 1-2.E(-15)之间]
示例:
I have a network array of 2 bytes that I need to convert to float
[values between -1 ... 1-2.E(-15)]
examples :
byte[] Arr1={0x70 , 0x54} //==> Result = 0.660
byte[] Arr2={0x10 , 0x37} //==> Result = 0.430
是否有解决方案可以超越此范围?
Any solutions to overpass this ?
推荐答案
您使用的哪种标准为您提供了 {0x70,0x54}
?
What standard you have used that gave you {0x70 , 0x54}
?
我已经按照 IEEE 754-2008
标准为半精度浮点对话制作了示例代码。
https://en.wikipedia.org/wiki/Half-precision_floating-point_format
I have made a sample code for Half-precision floating point conversation according to IEEE 754-2008
standard.
https://en.wikipedia.org/wiki/Half-precision_floating-point_format
public static float toTwoByteFloat(byte HO, byte LO)
{
var intVal = BitConverter.ToInt32(new byte[] { HO, LO, 0, 0 }, 0);
int mant = intVal & 0x03ff;
int exp = intVal & 0x7c00;
if (exp == 0x7c00) exp = 0x3fc00;
else if (exp != 0)
{
exp += 0x1c000;
if (mant == 0 && exp > 0x1c400)
return BitConverter.ToSingle(BitConverter.GetBytes((intVal & 0x8000) << 16 | exp << 13 | 0x3ff), 0);
}
else if (mant != 0)
{
exp = 0x1c400;
do
{
mant <<= 1;
exp -= 0x400;
} while ((mant & 0x400) == 0);
mant &= 0x3ff;
}
return BitConverter.ToSingle(BitConverter.GetBytes((intVal & 0x8000) << 16 | (exp | mant) << 13), 0);
}
private static byte[] I2B(int input)
{
var bytes = BitConverter.GetBytes(input);
return new byte[] { bytes[0], bytes[1] };
}
public static byte[] ToInt(float twoByteFloat)
{
int fbits = BitConverter.ToInt32(BitConverter.GetBytes(twoByteFloat), 0);
int sign = fbits >> 16 & 0x8000;
int val = (fbits & 0x7fffffff) + 0x1000;
if (val >= 0x47800000)
{
if ((fbits & 0x7fffffff) >= 0x47800000)
{
if (val < 0x7f800000) return I2B(sign | 0x7c00);
return I2B(sign | 0x7c00 | (fbits & 0x007fffff) >> 13);
}
return I2B(sign | 0x7bff);
}
if (val >= 0x38800000) return I2B(sign | val - 0x38000000 >> 13);
if (val < 0x33000000) return I2B(sign);
val = (fbits & 0x7fffffff) >> 23;
return I2B(sign | ((fbits & 0x7fffff | 0x800000) + (0x800000 >> val - 102) >> 126 - val));
}
您将像使用
private void button1_Click(object sender, EventArgs e)
{
var x = ToInt(0.660f); //it's 0x48 0x39
var y = toTwoByteFloat(x[0], x[1]); //it's 0.66015625
}
这篇关于将字节数组转换为16位浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文