我为C#写了一个CRC Xmodem代码,我不知道为什么它会溢出 [英] I wrote a CRC Xmodem code for C# and I don't know why it overflows

查看:52
本文介绍了我为C#写了一个CRC Xmodem代码,我不知道为什么它会溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using System;

namespace CRC2
{
	class Program
	{
		public static ushort[] crc_table =
		{
	    	0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
	    	0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef
		};
		
		public static ushort CalculateCrc( byte[] data )
		{
		    int i;
		    ushort crc = 0;
		    int len = data.Length;
		
		    for (int j = 0; j < len; j++)
		    {
		        i = ( crc >> 12 ) ^ ( data[j] >> 4 );
		        crc = (ushort) (crc_table[ i & 0x0F ] ^ ( crc << 4 ));
		        i = ( crc >> 12 ) ^ ( data[j] >> 0 );
		        crc = (ushort) (crc_table[ i & 0x0F ] ^ ( crc << 4 ));
		    }
		
		    return crc;
		}
		
		public static void Main(string[] args)
		{
			string a = "1";
			
			byte [] numero = new byte[256];

			for (int i=0;i<a.length;i++)>
			{
				numero[i]=(byte)a[i];
			}
			
			ushort CRC = CalculateCrc(numero);


			Console.Write("CRC: ");
			Console.Write(CRC);
			
			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
		}
	}
}

推荐答案

问题是第二部分的中间值crc计算:

The problem is the intermediate values in the second part of the crc calculation:
crc = (ushort) (crc_table[ i & 0x0F ] ^ ( crc << 4 ));



crc<<此行中的4大于0xFFFF,因此转换为ushort失败。

将一些额外的屏蔽添加到16位以确保其正常运行。

OR

未选中构造中包装for循环的内部。



旁白:只有在启用算术上溢/下溢检查时才会出现此症状,默认情况下不会这样做。


the value of crc << 4 in this line is greater than 0xFFFF so the cast to ushort fails.
Add some additional masking to 16 bits to ensure this behaves correctly.
OR
wrap the interior of the for loop in the unchecked construct.

Aside: This symptom only appears if arithmetic overflow/underflow checking is enabled, which, by default, it is not.


这篇关于我为C#写了一个CRC Xmodem代码,我不知道为什么它会溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆