37 lines
No EOL
938 B
C#
37 lines
No EOL
938 B
C#
using System;
|
|
using System.Text;
|
|
|
|
public static class Crc16IbmSdlc
|
|
{
|
|
private const ushort PolyReversed = 0x8408; // Reflected 0x1021
|
|
private const ushort Init = 0xFFFF;
|
|
private const ushort XorOut = 0xFFFF;
|
|
|
|
private static readonly ushort[] Table = new ushort[256];
|
|
|
|
static Crc16IbmSdlc()
|
|
{
|
|
for (ushort i = 0; i < 256; i++)
|
|
{
|
|
ushort value = i;
|
|
for (byte j = 0; j < 8; j++)
|
|
{
|
|
if ((value & 1) != 0)
|
|
value = (ushort)((value >> 1) ^ PolyReversed);
|
|
else
|
|
value >>= 1;
|
|
}
|
|
Table[i] = value;
|
|
}
|
|
}
|
|
|
|
public static ushort ComputeChecksum(ReadOnlySpan<byte> data)
|
|
{
|
|
ushort crc = Init;
|
|
foreach (byte b in data)
|
|
{
|
|
crc = (ushort)((crc >> 8) ^ Table[(crc ^ b) & 0xFF]);
|
|
}
|
|
return (ushort)(crc ^ XorOut);
|
|
}
|
|
} |