using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace JZLMonitor_V2._0
{
public class Check
{
/// <summary>
/// 校验和函数
/// </summary>
/// <param name="data">需要校验的数据</param>
/// <returns>返回的校验码</returns>
public static Int16 SumCheck(byte[] data, int Len)
{
Int16 Sum = 0x0000;
for (int i = 0; i < Len; i++)
{
Sum +=data[1+i];
}
return Sum;
}
/// <summary>
/// CRC16校验函数
/// </summary>
/// <param name="data">需要校验的数据</param>
/// <returns>返回的校验码</returns>
public static ushort CRC16(byte[] data,int Len)
{
const ushort polinomio = 0xA001;
ushort result = 0xFFFF;
for (int i = 0; i < Len; i++)
{
byte tmp = data[i];
result = (ushort)(tmp ^ result);
for (int j = 0; j < 8; j++)
{
if ((result & 0x0001) == 1)
{
result = (ushort)((result >> 1) ^ polinomio);
}
else
{
result = (ushort)(result >> 1);
}
}
}
ushort CRCResult = (ushort)((result << 8) + (result >> 8));
return CRCResult;
}
/*********************************************************************************
函数名称: GetCHKSUM
功能描述: 获取LENGTH的值
输 入: TempData:待解析的字节数组
输 出: 无
返 回 值: CHKSUM的值
作 者: 李 尧
日 期: 2011.09.06
修改记录:
*********************************************************************************/
public static ushort GetCHKSUM(byte[] TempData)
{
ushort CHKSUM = 0; //定义返回的16进制数CHKSUM
UInt16 temp = 0; //定义用于缓存的16进制变量temp
for (int i = 1; i < (TempData.Length - 3); i++)
{
if ((TempData[i] >> 4) <= 0x09) //判断字节数组当前的元素的高4位是否大于0x9,如果是,则让其加上0x30再赋值给temp的
{
temp += (UInt16)((TempData[i] >> 4) + 0x30);
}
else //判断字节数组当前的元素的高4位是否大于0x9,如果否,则让其加上0x37再赋值给temp的
{
temp += (UInt16)((TempData[i] >> 4) + 0x37);
}
if ((TempData[i] & 0x0F) <= 0x09) //判断字节数组当前的元素的低4位是否大于0x9,如果是,则让其加上0x30再赋值给temp的
{
temp += (UInt16)((TempData[i] & 0x0F) + 0x30);
}
else //判断字节数组当前的元素的低4位是否大于0x9,如果否,则让其加上0x37再赋值给temp的
{
temp += (UInt16)((TempData[i] & 0x0F) + 0x37);
}
}
CHKSUM = (UInt16)((~(temp % 65536)) + 1); //对所求的数据对应的Ascii值的和进行相应处理
return CHKSUM; //返回CHKSUM
}
/// <summary>
/// BCC校验码
/// </summary>
/// <param name="byData"></param>
/// <param name="iDataLen"></param>
/// <returns></returns>
public static byte GetBCCByte(byte[] byData, int iDataLen)
{
byte byDataBCC = 0; /* 赋初值 */
for (int i = 0; i < iDataLen; i++)
{
byDataBCC ^= byData[i + 1]; /* 循环异或和 */
}
return byDataBCC; /* 返回结果 */
}
}
}