1

I'm trying to use the code provided in this answer but I get a System.OverflowException on the line byte index = (byte)(crc ^ bytes[i]);
This happens on the next iteration after the first non-zero byte. I'm not sure what to check.

Thanks in advance.

SharpDevelop Version : 5.1.0.5134-RC-d5052dc5
.NET Version : 4.6.00079
OS Version : Microsoft Windows NT 6.3.9600.0

Community
  • 1
  • 1
asCii88
  • 23
  • 6
  • 1
    Using SharpDevelop is surely the underlying reason. Whether this code bombs depends on a compiler option, `/checked`. Always off by default in Visual Studio. Dig through the project setting dialog to find it. – Hans Passant Nov 12 '15 at 08:35

1 Answers1

1

It may be that you building with arithmetic overflow checking enabled, but the answer assumes that this is not the case. By default, checking is disabled, so it's not uncommon to see this assumption made.

In the code in question:

    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 is an unsigned short while index is a byte, so (crc ^ bytes[i]) could clearly be larger than 255 and make the conversion to byte overflow in a checked environment.

If I change the line to be explicitly unchecked:

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

Then the overflow no longer occurs.

dbc
  • 104,963
  • 20
  • 228
  • 340