using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace modbusCRC16
{
public class Classmodbus16CRC
{
public static byte[] k;// = new byte[] //{ 0x01, 0x03, 0x00, 0x01, 0x00, 0x02 };//需校验的数据
public string str; //= string.Empty;//初始化空值
public int t;
public byte[]bt = ToModbus(k);//调用校验数据
//==========字节转字符串函数
public static string strbytext(byte[] t, int b)
{
string str = string.Empty;
for (int i = 0; i < t.Length; i++)
{
str += t[i].ToString("X");//10->16
}
return str;
}
//============字节校验函数=====================================================================
public static byte[] ToModbus(byte[] byteData)
{
byte[] CRC = new byte[2];
UInt16 wCrc = 0xFFFF;
for (int i = 0; i < byteData.Length; i++)
{
wCrc ^= Convert.ToUInt16(byteData[i]);
for (int j = 0; j < 8; j++)
{
if ((wCrc & 0x0001) == 1)
{
wCrc >>= 1;
wCrc ^= 0xA001;//异或多项式
}
else
{
wCrc >>= 1;
}
}
}
CRC[1] = (byte)((wCrc & 0xFF00) >> 8);//高位在后
CRC[0] = (byte)(wCrc & 0x00FF); //低位在前
return CRC;
}
}
}