一般来说,通信协议中的通用数据格式是 包头+指令码+数据长度+有效数据+校验码+包尾。
其中,校验方式有多种,最流行的是CRC校验方式,其次是简单的奇偶性校验。校验码是根据上述方式来计算【除了包头包尾和校验码的其他字节】来得到的,也即是下面函数的入参。
废话不多说,直接上方法(感兴趣的话可以百度搜一下计算原理)
CRC校验生成的校验码是2个字节,奇偶性校验生成的是1个字节。
/// <summary>
/// CRC校验
/// </summary>
/// <param name="data">校验数据</param>
/// <returns>高低8位</returns>
public static byte[] CRCCalc(byte[] bytedata)
{
byte[] res = new byte[2];
byte[] crcbuf = bytedata.ToArray();
//计算并填写CRC校验码
int crc = 0xffff;
int len = crcbuf.Length;
for (int n = 0; n < len; n++)
{
byte i;
crc = crc ^ crcbuf[n];
for (i = 0; i < 8; i++)
{
int TT;
TT = crc & 1;
crc = crc >> 1;
crc = crc & 0x7fff;
if (TT == 1)
{
crc = crc ^ 0xa001;
}
crc = crc & 0xffff;
}
}
res[1] = (byte)((crc >> 8) & 0xff);
res[0] = (byte)((crc & 0xff));
return res;
}
奇偶性校验方式大家在网上很难搜到,我也是搜了挺久最后才发现很简单,其实就是把所有字节加起来得到的数,也叫奇偶和校验(其实还有所谓的奇校验和偶校验,这两种不常用反而混淆视听,在此不做赘述)。下面列出两种方式,一种是C常用,一种是C#累加
byte GetParity(byte[] SendBuf)
{
byte Parity = 0; //计算奇偶校验和
for (int i = 0; i < SendBuf.Length; i++)
{
Parity = (byte)(Parity ^ SendBuf[i]);
}
return Parity;
}
byte GetParity2(byte[] SendBuf)
{
byte Parity = 0; //计算奇偶校验和
for (int i = 0; i < SendBuf.Length; i++)
{
Parity = (byte)(Parity +SendBuf[i]);
}
return Parity;
}
如果对大家有用,别忘了点赞哟~~~感谢大家的鼓励!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)