C#实现CRC32算法

更新于 2024-10-10

CRC32 是一种校验和算法,用于检测消息是否未被修改。
它被广泛使用:例如,通过以太网发送包计算校验和。

public class CRC32
{
    private static readonly uint[] Crc32Table = new uint[256];
    static CRC32()
    {
        uint i, j;
        uint crc;
        for (i = 0; i < 256; i++)
        {
            crc = i;
            for (j = 0; j < 8; j++)
            {
                if ((crc & 1) > 0)
                    crc = (crc >> 1) ^ 0xEDB88320;
                else
                    crc >>= 1;
            }
            Crc32Table[i] = crc;
        }
    }

    public static byte[] Compute(byte[] data)
    {
        return Compute(data, 0, data.Length);
    }
    public static byte[] Compute(byte[] data, int offset, int count)
    {

        uint crc = ComputeUint(data, offset, count);

        return [
            (byte)((crc >> 24) & 0xff),
            (byte)((crc >> 16) & 0xff),
            (byte)((crc >> 8) & 0xff),
            (byte)(crc & 0xff),
        ];
    }
    public static uint ComputeUint(byte[] data)
    {

        return ComputeUint(data, 0, data.Length);
    }
    public static uint ComputeUint(byte[] data, int offset, int count)
    {

        uint crc = 0xffffffff;

        for (var i = offset; i < offset + count; i++)
        {
            crc = (crc >> 8) ^ Crc32Table[(crc ^ data[i]) & 0xff];
        }
        return crc ^ 0xffffffff;
    }
}