public class CRC16Helper
{
/// <summary>
/// CRC校验
/// </summary>
/// <param name="data">校验数据</param>
/// <returns>高低8位</returns>
public static string CRCCalc(string data)
{
string[] datas = data.Split(' ');
List<byte> bytedata = new List<byte>(); foreach (string str in datas)
{
bytedata.Add(byte.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier));
}
byte[] crcbuf = bytedata.ToArray();
//计算并填写CRC校验码
int crc = 0xffff;
int len = crcbuf.Length;
for (int n = ; n < len; n++)
{
byte i;
crc = crc ^ crcbuf[n];
for (i = ; i < ; i++)
{
int TT;
TT = crc & ;
crc = crc >> ;
crc = crc & 0x7fff;
if (TT == )
{
crc = crc ^ 0xa001;
}
crc = crc & 0xffff;
} }
string[] redata = new string[];
redata[] = Convert.ToString((byte)((crc >> ) & 0xff), );
redata[] = Convert.ToString((byte)((crc & 0xff)), );
return data + " " + redata[] + " " + redata[];
} /// <summary>
/// CRC校验
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static byte[] CRC16(byte[] bytes)
{
//计算并填写CRC校验码
int crc = 0xffff;
int len = bytes.Length;
for (int n = ; n < len; n++)
{
byte i;
crc = crc ^ bytes[n];
for (i = ; i < ; i++)
{
int TT;
TT = crc & ;
crc = crc >> ;
crc = crc & 0x7fff;
if (TT == )
{
crc = crc ^ 0xa001;
}
crc = crc & 0xffff;
} } var nl = bytes.Length + ;
//生成的两位校验码
byte[] redata = new byte[];
redata[] = (byte)((crc & 0xff));
redata[] = (byte)((crc >> ) & 0xff); //重新组织字节数组
var newByte = new byte[nl];
for (int i = ; i < bytes.Length; i++)
{
newByte[i] = bytes[i];
}
newByte[nl - ] = (byte)redata[];
newByte[nl -] = redata[]; return newByte;
}
}

第一个方法是把校验位返回,返回的是字符串

第二个是在第一个的基础上改的,返回的是加了校验位之后的数据,字节数组。

说明:代码来自好互联网。

05-24 06:44