常见CRC算法模型如下:
CRC校验工具-在线工具
1)python
binascii.crc_hqx crcmod.mkCrcFun
Python binascii.crc_hqx方法代碼示例 - 純淨天空
Python Examples of crcmod.mkCrcFun
crcmod – CRC calculation — crcmod v1.7 documentation
2)c#版本
public enum Crc16Mode : ushort { Standard = 0xA001, CcittKermit = 0x8408 }
public class Crc16
{
readonly ushort[] table = new ushort[256];
public ushort ComputeChecksum(params byte[] bytes)
{
ushort crc = 0;
for (int i = 0; i < bytes.Length; ++i)
{
byte index = (byte)(crc ^ bytes[i]);
crc = (ushort)((crc >> 8) ^ table[index]);
}
return crc;
}
public ushort ComputeChecksumCanny(params byte[] bytes)
{
ushort crc = 0;
for (int i = 0; i < bytes.Length; ++i)
{
byte index = (byte)((crc>>8) ^ bytes[i]);
crc = (ushort)((crc << 8) ^ table[index]);
}
return crc;
}
public ushort ComputeChecksumCanny2(ushort crcInit,params byte[] bytes)
{
ushort crc = crcInit;
for (int i = 0; i < bytes.Length; ++i)
{
byte index = (byte)((crc>>8) ^ bytes[i]);
crc = (ushort)((crc << 8) ^ table[index]);
}
return crc;
}
public byte[] ComputeChecksumBytes(params byte[] bytes)
{
ushort crc = ComputeChecksum(bytes);
return BitConverter.GetBytes(crc);
}
public Crc16(Crc16Mode mode)
{
ushort polynomial = (ushort)mode;
ushort value;
ushort temp;
for (ushort i = 0; i < table.Length; ++i)
{
value = 0;
temp = i;
for (byte j = 0; j < 8; ++j)
{
if (((value ^ temp) & 0x0001) != 0)
{
value = (ushort)((value >> 1) ^ polynomial);
}
else
{
value >>= 1;
}
temp >>= 1;
}
table[i] = value;
//Console.WriteLine($"0x{table[i]:x2}");
}
}
}
var crc16 = new Crc16(Crc16Mode.CcittKermit);
var fileWithLocation = "D:\21100815.165";
byte[] bytes = File.ReadAllBytes(fileWithLocation);
Console.WriteLine($"file size:{bytes.Length} bytes");
var crc16Ret = crc16.ComputeChecksum(bytes);
var aa = crc16Ret;
Console.WriteLine($"org CRC16:0x{aa:x2}");
crc16Ret = crc16.ComputeChecksumCanny(bytes);
aa = crc16Ret;
Console.WriteLine($"Canny CRC16:0x{aa:x2}");
A Standard CRC-16 and CRC-16 Kermit implementation in C# - Sanity Free Coding - C#, .NET, PHP



