无法将'int'隐式转换成'ushort',存在一个显示转换(是否缺少强制转换)
c#翻译c时出错(如题),刚学c#一时找不到办法解决,高人能否指点下
C code:
const unsigned short cnCRC_16 = 0x8005;
unsigned long Table_CRC[256]; // CRC 表
unsigned short CRC_16( unsigned char * aData, unsigned long aSize )
{
unsigned long i;
unsigned short nAccum = 0;
BuildTable16( cnCRC_16 ); // or cnCRC_CC99vT
for ( i = 0; i < aSize; i++ )
nAccum = ( nAccum << 8 ) ^ ( unsigned short )Table_CRC[( nAccum >> 8 ) ^ *aData++];
return nAccum;
}
*******************************************************
c#:
public const ushort cnCRC_16 = 0x8005;
public UInt32[] Table_CRC_16 = new UInt32[256];
public ushort CRC16(ref byte[] aData, UInt32 aSize)
{
UInt32 i;
ushort nAccum = 0;
for (i = 0; i <aSize; i++)
{
nAccum = (nAccum << 8) ^ (ushort) Table_CRC_16[(nAccum >> 8) ^ aData[i]];//这里提示出错(如题)
}
return nAccum;
}
------解决方案--------------------把ushort换成uint。
------解决方案--------------------ushort 0 到 65,535
int -2,147,483,648 到 2,147,483,647
int -> ushort 需要强制转换类型
C# code
ushort i = 65535;
int i1 = 655350;
//i = i1;
i = (ushort)i1;
------解决方案--------------------
这说明C#是一种比C更严格的语言——在C中允许你将整数转换为短整数,并且不会考虑溢出问题,对于新手来说,这会使得他们编写出不可靠的程序。
------解决方案--------------------
=》
C# code
nAccum = (ushort)((nAccum << 8) ^ Table_CRC_16[(nAccum >> 8) ^ aData[i]]);