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
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.