从modbus接收到的数据,转为浮点数:
float f = GetFloat(registerBuffer[0], registerBuffer[1]); public static float GetFloat(ushort P1, ushort P2) { int intSign, intSignRest, intExponent, intExponentRest; float faResult, faDigit; intSign = P1 / 32768; intSignRest = P1 % 32768; intExponent = intSignRest / 128; intExponentRest = intSignRest % 128; faDigit = (float)(intExponentRest * 65536 + P2) / 8388608; faResult = (float)Math.Pow(-1, intSign) * (float)Math.Pow(2, intExponent - 127) * (faDigit + 1); return faResult; }
将浮点数转为modbus需要的无符号短整数:
float fff = float.Parse(floattxt.Text); string d = BitConverter.ToString(BitConverter.GetBytes(fff).Reverse().ToArray()).Replace("-", ""); Console.WriteLine(d); ushort ss1 = Convert.ToUInt16(d.Substring(0,4),16); ushort ss2 = Convert.ToUInt16(d.Substring(3, 4), 16);