我有以下CRC功能:
public static ushort ComputeCRC16(byte[] data)
{
ushort i, j, crc = 0;
int size = data.Length;
for (i = 0; i < size - 2; i++)
{
crc ^= (ushort)(data[i] << 8);
for (j = 0; j < 8; j++)
{
if ((crc & 0x8000) != 0) /* Test for bit 15 */
{
crc = (ushort)((crc << 1) ^ 0x1234); /* POLYNOMIAL */
}
else
{
crc <<= 1;
}
}
}
return crc;
}
Run Code Online (Sandbox Code Playgroud)
我一直在试图用它来计算从一个文件即大约800 KB一个CRC16,但它需要永远,我的意思是五分钟后,价值i仍约为2 000,它应该上升到800万人.
有人可以给我解释为什么它如此缓慢以及我可以做些什么来解决这个问题?
我在i7处理器上使用Visual Studio 2015,计算机不老也不破.
将第一行替换为:
int i, j;
ushort crc = 0;
Run Code Online (Sandbox Code Playgroud)
您使用的ushort是for计数器,但如果size> 65535,则for循环不会结束.
这样做的原因是,如果发生溢出,C#默认不会抛出异常但只是"默默地"忽略它.查看以下代码以进行演示:
ushort i = ushort.MaxValue; //65535
i++; //0
Run Code Online (Sandbox Code Playgroud)