我从ISO/IEC JTC1/SC17 N 3497中的 C 代码中颠倒了这一点,所以它并不漂亮,但可以满足您的需要:
public class CrcB
{
const ushort __crcBDefault = 0xffff;
private static ushort UpdateCrc(byte b, ushort crc)
{
unchecked
{
byte ch = (byte)(b^(byte)(crc & 0x00ff));
ch = (byte)(ch ^ (ch << 4));
return (ushort)((crc >> 8)^(ch << 8)^(ch << 3)^(ch >> 4));
}
}
public static ushort ComputeCrc(byte[] bytes)
{
var res = __crcBDefault;
foreach (var b in bytes)
res = UpdateCrc(b, res);
return (ushort)~res;
}
}
作为测试,请尝试以下代码:
public static void Main(string[] args)
{
// test case 1 0xFC, 0xD1
var bytes = new byte[] { 0x0F, 0xAA, 0xFF };
var crc = CrcB.ComputeCrc(bytes);
var cbytes = BitConverter.GetBytes(crc);
Console.WriteLine("First (0xFC): {0:X}\tSecond (0xD1): {1:X}", cbytes[0], cbytes[1]);
// test case 2 0xCC, 0xC6
bytes = new byte[] { 0x00, 0x00, 0x00 };
crc = CrcB.ComputeCrc(bytes);
cbytes = BitConverter.GetBytes(crc);
Console.WriteLine("First (0xCC): {0:X}\tSecond (0xC6): {1:X}", cbytes[0], cbytes[1]);
Console.ReadLine();
}