|
- public class KModbusUnity
- {
- static ushort POLYNOMIAL = 0xA001;
- /// <summary>
- /// 計算CRC校驗結(jié)果
- /// </summary>
- /// <param name="data">數(shù)據(jù)源</param>
- /// <returns>校驗結(jié)果</returns>
- public static byte[] CRCCheck(byte[] data )
- {
- ushort crc = 0xffff;
- for(ushort i=0;i<data.Length;i++)
- {
- crc ^= (ushort)(data[i] & 0x00FF);
- for(ushort j = 0;j<8;j++)
- {
- if ((crc & 0x0001) != 0)
- {
- crc >>= 1;
- crc ^= POLYNOMIAL;
- }
- else
- crc >>= 1;
- }
- }
- return System.BitConverter.GetBytes(crc);
- }
- /// <summary>
- /// 收到的數(shù)據(jù)有效
- /// </summary>
- /// <param name="data">數(shù)據(jù)</param>
- /// <returns></returns>
- public static bool IsValid(byte[] data)
- {
- bool bReturn = false;
- int n = data.Length;
- if (n >= 4)
- {
- byte[] check = new byte[n - 2];
- for (int j = 0; j < n - 2; j++)
- {
- check[j] = data[j];
- }
- // 校驗結(jié)果
- byte[] crc = KModbusUnity.CRCCheck(check);
- if (crc[0] == data[n - 2] && crc[1] == data[n - 1])
- {
- bReturn = true;
- }
- }
- return bReturn;
- }
- /// <summary>
- /// 返回帶校驗碼的數(shù)據(jù)
- /// </summary>
- /// <param name="data">源數(shù)據(jù)</param>
- /// <returns>帶校驗碼的數(shù)據(jù)</returns>
- public static byte[] CRCData(byte[] data)
- {
- byte[] crcCheck = CRCCheck(data);
- byte[] rdata = new byte[data.Length + 2];
- data.CopyTo(rdata, 0);
- crcCheck.CopyTo(rdata, data.Length);
- return rdata;
- }
- public static byte[] CRCData(String hex)
- {
- return CRCData(HexStrToBytes(hex));
- }
- /// <summary>
- /// 16進(jìn)制字符串轉(zhuǎn)byte數(shù)組
- /// </summary>
- /// <param name="hex">16進(jìn)制的字符串,可以是空格隔開的方式</param>
- /// <returns>byte數(shù)組</returns>
- public static byte[] HexStrToBytes(String hex)
- {
- hex = hex.Replace(" ", "");
- if ((hex.Length % 2) != 0)
- hex += " ";
- byte[] returnBytes = new byte[hex.Length / 2];
- for (int i = 0; i < returnBytes.Length; i++)
- {
- String sub = hex.Substring(i * 2, 2);
- returnBytes[i] = Convert.ToByte(sub, 16);
- }
- return returnBytes;
- }
- /// <summary>
- /// byte數(shù)組轉(zhuǎn)16進(jìn)制字符串
- /// </summary>
- /// <param name="bytes">byte數(shù)組</param>
- /// <returns>16進(jìn)制字符串</returns>
- public static String BytesToHexStr(byte[] bytes)
- {
- return BitConverter.ToString(bytes).Replace('-', ' ').Trim();
- }
- /// <summary>
- /// byte轉(zhuǎn)float
- /// </summary>
- /// <param name="data">byte</param>
- /// <param name="nStart">開始位置</param>
- /// <returns>float</returns>
- public static float BytesToFloat(byte[] data ,int nStart = 0)
- {
- float fResult = 0;
-
- fResult = BitConverter.ToSingle(new byte[] {data[nStart+3],data[nStart+2],data[nStart+1],data[nStart] }, 0);
- return fResult;
- }
- public static bool[] ByteToBitArray(byte data)
- {
- bool[] bResult = new bool[8];
- for(int i =0;i<8;i++)
- {
- var tmp = 1 << i;
- bool b = ((data & tmp) == tmp);
- bResult[i] = b;
- }
- return bResult;
- }
- public static byte[] StringToBytes(String str)
- {
- return System.Text.Encoding.ASCII.GetBytes(str);
- }
- }
復(fù)制代碼
|
|