C#实现物联网系统温度解析的函数(支持补码)
基于物联网协议上传数据,其中温度占两个字节,如01 27,表示温度值为29.7。温度负值为补码(也就是温度值为有符号数),例如0XFFFF值为负1(-0.1度)。
针对补码要求,修改数据解析函数如下:
public object Parser(byte[] bytes, int nLen) { /* 补码左侧最高位为符号位,0表示整数,1表示负数。 正整数的补码是其二进制表示,与原码相同 将其对应正数二进制表示所有位(不包括符号位)取反(0变1,1变0,符号位为1不变)后加1 */ if (bytes == null || bytes.Length == 0) return 0; byte byte1 = bytes[0]; int seedNum = 1; int bitNum = 7; seedNum = seedNum << bitNum; int result = byte1 & seedNum; if (result == 0)//正数 { string hexStr = FunLIB.ByteToHexString(bytes, nLen, false); return (float)Convert.ToInt32(hexStr, 16); } else if (result == seedNum)//负数 { string hexStr = FunLIB.ByteToHexString(bytes, nLen, false); int intResult = Convert.ToInt32(hexStr, 16); //转为二进制字符串 string sBin = Convert.ToString(intResult, 2); //取反 StringBuilder sb = new StringBuilder(); foreach (char ch in sBin) { if (ch == '1') sb.Append("0"); else sb.Append("1"); } string sBin2 = sb.ToString(); //转换为整数后+1 int n = Convert.ToInt32(sBin2, 2); n = (n + 1) * -1; return (float)n; } return 0; }