c# - convert byte array to 16 bits float -
i have network array of 2 bytes need convert 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 overpass ?
what standard have used gave {0x70 , 0x54}
?
i have made sample code half-precision floating point conversation according 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; { 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)); }
you'll use following
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 }
Comments
Post a Comment