System.OverflowException 在 C# 上计算 CRC-16

System.OverflowException computing CRC-16 on C#

我正在尝试使用 this answer 中提供的代码,但我在行 byte index = (byte)(crc ^ bytes[i]); 上得到一个 System.OverflowException
这发生在第一个非零字节。我不确定要检查什么。

提前致谢。

SharpDevelop 版本:5.1.0.5134-RC-d5052dc5
.NET 版本:4.6.00079
OS 版本:微软 Windows NT 6.3.9600.0

可能是您使用 arithmetic overflow checking enabled, but the answer assumes that this is not the case. By default, checking is disabled 进行构建,因此这种假设并不罕见。

在有问题的代码中:

    public static ushort ComputeChecksum(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;
    }

crc 是一个无符号的短整数,而 index 是一个字节,所以 (crc ^ bytes[i]) 显然可以大于 255 并在检查中转换为 byte 溢出环境。

如果我将行更改为显式 unchecked:

            byte index = unchecked((byte)(crc ^ bytes[i]));

那么溢出就不会再发生了。