C# CRC16计算校验域

/// <summary>
/// 计算校验域(CRC16)
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] CRC16(byte[] data)
{
int len = data.Length;
if (len > 0)
{
ushort crc = 0xFFFF;

for (int i = 0; i < len; i++)
{
crc = (ushort)(crc ^ (data[i]));
for (int j = 0; j < 8; j++)
{
crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
}
}
byte hi = (byte)((crc & 0xFF00) >> 8); //高位置
byte lo = (byte)(crc & 0x00FF); //低位置

return new byte[] { hi, lo };
}
return new byte[] { 0, 0 };
}

posted @ 2023-02-10 14:55  YuanY  阅读(159)  评论(0编辑  收藏  举报