2013-04-18 67 views
1

基于Online CRC calculation,当我进入十六进制字符串数据=缺少CRC-CCITT(0xFFFF)?

我得到的结果CRC-CCITT(0xFFFF的) =

0x354E(预期结果)

我使用下面的代码,但结果CalcCRC16()0xACEE。以下缺少什么脚本?

using System; 
using System.Windows.Forms; 
using System.Runtime.Remoting.Metadata.W3cXsd2001; 
using System.Diagnostics; 

namespace WindowsFormsApplication1 { 
    public partial class Form1 : Form { 

     public Form1() { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) { 
      string result = CalcCRC16("503002080000024400003886030400000000010100");    
      Debug.Print(result); 
      // result = ACEE 
      // result expected = 354E 
     } 

     // CRC-CCITT (0xFFFF) with poly 0x1021 
     // input (hex string) = "503002080000024400003886030400000000010100" 
     // result expected (hex string) = "354E" 
     public string CalcCRC16(string strInput) { 
      ushort temp = 0; 
      ushort crc = 0xFFFF; 
      byte[] bytes = GetBytesFromHexString(strInput); 
      for (int j = 0; j < bytes.Length; j++) { 
       crc = (ushort)(crc^bytes[j]); 
       for (int i = 0; i < 8; i++) { 
        if ((crc & 0x0001) == 1) 
         crc = (ushort)((crc >> 1)^0x1021); 
        else 
         crc >>= 1; 
       } 
      } 
      crc = (ushort)~(uint)crc; 
      temp = crc; 
      crc = (ushort)((crc << 8) | (temp >> 8 & 0xFF)); 
      return crc.ToString("X4"); 
     } 

     public Byte[] GetBytesFromHexString(string strInput) { 
      Byte[] bytArOutput = new Byte[] { }; 
      if (!string.IsNullOrEmpty(strInput) && strInput.Length % 2 == 0) { 
       SoapHexBinary hexBinary = null; 
       try { 
        hexBinary = SoapHexBinary.Parse(strInput); 
        if (hexBinary != null) 
         bytArOutput = hexBinary.Value; 
       } 
       catch (Exception ex) { 
        MessageBox.Show(ex.Message); 
       } 
      } 
      return bytArOutput; 
     } 

    } 
} 

回答

2

我找到了答案,我会在这里分享..可能对他人有用。

strInput = 503002080000024400003886030400000000010100

初始= 0xFFFF的

聚= 0x1021

strOutput = 354E

参考= Online CRC Calc

public string CalcCRC16(string strInput) { 
    ushort crc = 0xFFFF; 
    byte[] data = GetBytesFromHexString(strInput); 
    for (int i = 0; i < data.Length; i++) { 
     crc ^= (ushort)(data[i] << 8); 
     for (int j = 0; j < 8; j++) { 
      if ((crc & 0x8000) > 0) 
       crc = (ushort)((crc << 1)^0x1021); 
      else 
       crc <<= 1; 
     } 
    } 
    return crc.ToString("X4"); 
} 

public Byte[] GetBytesFromHexString(string strInput) { 
    Byte[] bytArOutput = new Byte[] { }; 
    if (!string.IsNullOrEmpty(strInput) && strInput.Length % 2 == 0) { 
     SoapHexBinary hexBinary = null; 
     try { 
      hexBinary = SoapHexBinary.Parse(strInput); 
      if (hexBinary != null) { 
       bytArOutput = hexBinary.Value; 
      } 
     } 
     catch (Exception ex) { 
      MessageBox.Show(ex.Message); 
     } 
    } 
    return bytArOutput; 
} 
+0

您的代码很容易转换为C,并且完美地工作。 – Zac 2015-01-12 16:51:16