public static class CommunicationHelper
{
private static uint crc;//CRC
#region CRC计算,传入要校验的字节数组,返回已经计算好的数组
public static byte[] GetCRCBytes(byte[] crcbuf)
{
byte[] bytes = new byte[crcbuf.Length + 2];
crcbuf.CopyTo(bytes, 0);
crc = 0xffff;
for (int i = 0; i < crcbuf.Length; i++)
{
calccrc(crcbuf[i]);
}
bytes[crcbuf.Length] = Convert.ToByte(crc & 0xff);
bytes[crcbuf.Length + 1] = Convert.ToByte(crc / 0x100);
return bytes;
}
#endregion
#region CRC计算,传入要校验的字节数组,返回验证结果
public static bool CRCCheck(byte[] crcbuf)
{
bool flag = false; ;
uint crc = 0xffff;
int l = crcbuf.Length;
byte crc16lo;
byte crc16hi;
if (l > 2)
{
crc16lo = crcbuf[l - 2];
crc16hi = crcbuf[l - 1];
byte i;
for (int j = 0; j < l - 2; j++)
{
crc = crc ^ crcbuf[j];
for (i = 0; i < 8; i++)
{
byte TT;
TT = Convert.ToByte(crc & 1);
crc = crc >> 1;
crc = crc & 0x7fff;
if (TT == 1)
crc = crc ^ 0xa001;
crc = crc & 0xffff;
}
}
byte crc16loafter = Convert.ToByte(crc & 0xff);
byte crc16hiafter = Convert.ToByte(crc / 0x100);
if (crc16loafter == crc16lo && crc16hiafter == crc16hi)
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
#endregion
#region CRC计算每个发送的字节
public static void calccrc(byte crcbuf)
{
byte i;
crc = crc ^ crcbuf;
for (i = 0; i < 8; i++)
{
byte TT;
TT = Convert.ToByte(crc & 1);
crc = crc >> 1;
crc = crc & 0x7fff;
if (TT == 1)
crc = crc ^ 0xa001;
crc = crc & 0xffff;
}
}
#endregion
#region 字符串转十六进制字节数组
public static byte[] HexStr2Byte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
{
hexString += " ";
}
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
{
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return returnBytes;
}
#endregion
#region 将字节数组转为 十六进制
public static string Byte2HexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
//if (returnStr.Substring(returnStr.Length - 1, 1) == " ")
//{
// returnStr = returnStr.Substring(0, returnStr.Length - 1);
//}
return returnStr;
}
#endregion
#region 翻转字符串
public static string StrReverse(string str)
{
int length = str.Length;
string strReverse = "";
for (int i = length - 1; i >= 0; i--)
{
strReverse += str.Substring(i, 1);
}
return strReverse;
}
#endregion
}
本文深入探讨了CRC校验算法的实现细节,包括CRC计算、校验和字节处理等核心功能。通过具体代码示例,展示了如何计算CRC校验值并验证数据的完整性。

745

被折叠的 条评论
为什么被折叠?



