将字节数组转换为16位浮点数

时间:2016-06-11 04:14:34

标签: c# byte

我有一个2字节的网络数组,我需要转换为float [值介于-1 ... 1-2.E(-15)]之间 例子:

byte[] Arr1={0x70 , 0x54} //==> Result = 0.660
byte[] Arr2={0x10 , 0x37} //==> Result = 0.430

任何解决方案都要超越这个?

2 个答案:

答案 0 :(得分:4)

您使用了什么标准给了@pytest.fixture(scope="class") def oneTimeSetUp(request, browser): print("Running one time setUp") if browser == 'firefox': driver = webdriver.Firefox() driver.maximize_window() driver.implicitly_wait(3) print("Running tests on FF") else: driver = webdriver.Chrome() print("Running tests on chrome") if request.cls is not None: request.cls.driver = driver

我根据{0x70 , 0x54}标准制作了半精度浮点对话的示例代码 https://en.wikipedia.org/wiki/Half-precision_floating-point_format

IEEE 754-2008

您将像以下

一样使用它
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));
}

答案 1 :(得分:0)

已经回答了这个问题,字节的值是一个pourcentage,因此它必须除以32767 例如:byte[] Arr1={0x70 , 0x54} //==> Result =0x5470/0x7fff= 0.660 byte[] Arr2={0x10 , 0x37} //==> Result = 0x3710/0x7fff= 0.430