我在网络上找了许多的CRC例子,改为C#之后的校验总是出错,不知道为啥在厂商提供给我的一个测试软件中,02 03 00 00 00 04得CRC16 是44 3A 可是我做出来的竟然是CF FC
赶紧救命,厂商来的设备已经很迟了,所以我得工期很紧

解决方案 »

  1.   

    注意,必须双字节调用 public static void CalculateCRC(byte [] pByte, int nNumberOfBytes, ref ushort pChecksum)
    {
    try
    {
    int nBit;
    ushort nShiftedBit;
    pChecksum = 0xFFFF; for (int nByte = 0; nByte < nNumberOfBytes; nByte++)
    {
    pChecksum ^= pByte[nByte]; for (nBit = 0; nBit < 8; nBit++)
    {
    if((pChecksum & 0x1) == 1)
    {
    nShiftedBit = 1;
    }
    else
    {
    nShiftedBit = 0;
    } pChecksum >>= 1;
    if(nShiftedBit != 0)
    {
    pChecksum ^= 0xA001;
    }
    }
    }
    }
    catch(Exception ex)
    {
    throw ex;
    }
    }
    public static string CalculateCRC(string p_strSrc)
    {
    try
    {
    byte[] m_BT = new byte[p_strSrc.Length/2];
    ushort m_Checksum = 0xFFFF; for(int i=0;i<p_strSrc.Length/2;i++)
    {
    m_BT[i] = Convert.ToByte(p_strSrc.Substring(i*2,2), 16);
    } CalculateCRC(m_BT, m_BT.Length, ref m_Checksum); string m_strChecksum = Convert.ToString(m_Checksum, 16).ToUpper(); m_strChecksum = m_strChecksum.Substring(2,2) + m_strChecksum.Substring(0,2); return m_strChecksum;
    }
    catch(Exception ex)
    {
    throw ex;
    }
    }
      

  2.   

    其实也不应该说是双字节,就是必须把02 03 00 00 00 04当成十六进制的调用
    例如
    byte[] bt = new byte[6];bt[0] = 0x02;
    bt[1] = 0x03;
    bt[2] = 0x00;
    bt[3] = 0x00;
    bt[4] = 0x00;
    bt[5] = 0x04;然后进行调用ushort m_Checksum = 0xFFFF;CalculateCRC(bt, bt.Length, ref m_Checksum)