You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
using System.Text;
|
|
|
|
|
|
|
|
|
|
namespace Service.Fire.Common;
|
|
|
|
|
|
|
|
|
|
public class CRC16
|
|
|
|
|
{
|
|
|
|
|
private const ushort Polynomial = 0x1021;
|
|
|
|
|
private ushort[] crcTable = new ushort[256];
|
|
|
|
|
|
|
|
|
|
public CRC16()
|
|
|
|
|
{
|
|
|
|
|
for (int i = 0; i < 256; i++)
|
|
|
|
|
{
|
|
|
|
|
ushort value = 0;
|
|
|
|
|
ushort temp = (ushort)(i << 8);
|
|
|
|
|
for (byte j = 0; j < 8; j++)
|
|
|
|
|
{
|
|
|
|
|
if (((value ^ temp) & 0x8000) != 0)
|
|
|
|
|
{
|
|
|
|
|
value = (ushort)((value << 1) ^ Polynomial);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
value = (ushort)(value << 1);
|
|
|
|
|
}
|
|
|
|
|
temp = (ushort)(temp << 1);
|
|
|
|
|
}
|
|
|
|
|
crcTable[i] = value;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public ushort ComputeChecksum(byte[] bytes)
|
|
|
|
|
{
|
|
|
|
|
ushort crc = 0xFFFF; // 初始值
|
|
|
|
|
for (int i = 0; i < bytes.Length; i++)
|
|
|
|
|
{
|
|
|
|
|
byte index = (byte)((crc ^ bytes[i]) & 0xff);
|
|
|
|
|
crc = (ushort)((crc >> 8) ^ crcTable[index]);
|
|
|
|
|
}
|
|
|
|
|
return crc;
|
|
|
|
|
}
|
|
|
|
|
}
|