我之前用的这个
#region CRC16校验
/// <summary>
///CRC16校验算法,(低字节在前,高字节在后)
/// </summary>
/// <param name="data">要校验的数组</param>
/// <returns>返回校验结果,低字节在前,高字节在后</returns>
public static byte[] crc16(byte[] data)
{
if (data.Length == 0)
throw new Exception("调用CRC16校验算法,(低字节在前,高字节在后)时发生异常,异常信息:被校验的数组长度为0。");
byte[] temdata = new byte[data.Length + 2];
int xda, xdapoly;
byte i, j, xdabit;
xda = 0xFFFF;
xdapoly = 0xA001;
for (i = 0; i < data.Length; i++)
{
xda ^= data[i];
for (j = 0; j < 8; j++)
{
xdabit = (byte)(xda & 0x01);
xda >>= 1;
if (xdabit == 1)
xda ^= xdapoly;
}
}
temdata = new byte[2] { (byte)(xda & 0xFF), (byte)(xda >> 8) };
return temdata;
}
#endregion
}
#region CRC16校验
/// <summary>
///CRC16校验算法,(低字节在前,高字节在后)
/// </summary>
/// <param name="data">要校验的数组</param>
/// <returns>返回校验结果,低字节在前,高字节在后</returns>
public static byte[] crc16(byte[] data)
{
if (data.Length == 0)
throw new Exception("调用CRC16校验算法,(低字节在前,高字节在后)时发生异常,异常信息:被校验的数组长度为0。");
byte[] temdata = new byte[data.Length + 2];
int xda, xdapoly;
byte i, j, xdabit;
xda = 0xFFFF;
xdapoly = 0xA001;
for (i = 0; i < data.Length; i++)
{
xda ^= data[i];
for (j = 0; j < 8; j++)
{
xdabit = (byte)(xda & 0x01);
xda >>= 1;
if (xdabit == 1)
xda ^= xdapoly;
}
}
temdata = new byte[2] { (byte)(xda & 0xFF), (byte)(xda >> 8) };
return temdata;
}
#endregion
}
解决方案 »
- DataGridView如何只删除选中Checked的项啊?
- 有几个page页面,如何实现点击page1上的按钮调出page2?
- 为什么福州的软件公司都只招收JAVA 和ASP的,都没几家有招ASP.NET 2.0(C#)方向的?
- 程序集问题 请高手进来指教
- 我问一下如何打包C#开发的程序?
- barmanage
- 求助编写windows服务遇到的问题,请朋友们帮我看看这个代码哪里有问题,谢谢!!
- 在c#下如何实现类似MFC中HitTest的功能?
- 360真心的玩具
- 各位,你们的电脑配置是什么,我是否要升级呀!
- WPF,TextBox为什么弄丢了字符串
- World Wide Web Publishing Service 总是手工 Start 后过不到1分钟它又自动 Stop
调用方式如下:
var crc = Crc.crc16(byteMessage);
var x = BitConverter.ToUInt16(crc,0);
var y = new byte[2];
y[0] = byteMessage[4];
y[1] = byteMessage[5];
var yy = BitConverter.ToUInt16(y,0);其中x=374,yy=9555,这个2个不匹配啊
{
ushort cRc_16 = 0x0000; // 初始化
const ushort cnCRC_16 = 0x8005;
uint[] cRctable_16=new uint[256];
ushort i,j,k;
int index=0;
for (i=0,k=0;i<256;i++,k++)
{
cRc_16 =(ushort)( i<<8);
for (j=8;j>0;j--)
{
if ((cRc_16&0x8000)>0) //反转时cRc_16&0x0001
cRc_16 =(ushort)( (cRc_16<<=1)^cnCRC_16); //反转时cRc_16=(cRc_16>>=1)^gEnpoly
else
cRc_16<<=1; //反转时cRc_16>>=1
}
cRctable_16[k] = cRc_16;
}
while (nLength>0)
{
cRc_16 = (ushort)((cRc_16 << 8) ^ cRctable_16[((cRc_16>>8) ^ pData[index]) & 0xff]);
nLength--;
index++;
}
return cRc_16;
}
CalcCrc16(byteMessage, byteMessage.Length);或者CalcCrc16(byteMessage, 1);
得到的结果和
var y = new byte[2];
y[0] = byteMessage[4];
y[1] = byteMessage[5];
var yy = BitConverter.ToUInt16(y, 0);
不匹配,是我调用的问题吗?
CalcCrc16(byteMessage, byteMessage.Length);或者CalcCrc16(byteMessage, 1);
得到的结果和
var y = new byte[2];
y[0] = byteMessage[4];
y[1] = byteMessage[5];
var yy = BitConverter.ToUInt16(y, 0);
不匹配,是我调用的问题吗?不是说第5和6,2个字节为校验和吗?这两个字节的结果跟CRC校验值应该不一样吧,一个是和校验,一个是CRC校验不知道你原来C++的校验代码对不对,我自己用的CRC校验算法跟3楼是一样的,初始值用的是0xFFFF,异或值用的是0xA001。而楼主用的是0x0000和0x8005,楼主这种算法我没用过