2011-10-05 40 views
1

我目前正在努力的方式需要使用公式(X16 + X12 + X5 + 1)的CRC_CCITT Kermit 16协议。然而,我在网上或网上找到的一些代码,一般来说我似乎没有得到我想要的结果。我看到了这个网站(http://www.lammertbies.nl/comm/info/crc-calculation.html),它实际上为我提供了我想要的精确匹配,但它是用C++编写的。那么有谁能帮我解决这个问题?C#中的CRC_CCITT Kermit 16#

我期待着您的回音。

亲切的问候

迈克尔

回答

0

看来想要CRC16 CCITT。试试这个:

using System; 

public enum InitialCrcValue { Zeros, NonZero1 = 0xffff, NonZero2 = 0x1D0F } 

public class Crc16Ccitt { 
    const ushort poly = 4129; 
    ushort[] table = new ushort[256]; 
    ushort initialValue = 0; 

    public ushort ComputeChecksum(byte[] bytes) { 
     ushort crc = this.initialValue; 
     for(int i = 0; i < bytes.Length; ++i) { 
      crc = (ushort)((crc << 8)^table[((crc >> 8)^(0xff & bytes[i]))]); 
     } 
     return crc; 
    } 

    public byte[] ComputeChecksumBytes(byte[] bytes) { 
     ushort crc = ComputeChecksum(bytes); 
     return BitConverter.GetBytes(crc); 
    } 

    public Crc16Ccitt(InitialCrcValue initialValue) { 
     this.initialValue = (ushort)initialValue; 
     ushort temp, a; 
     for(int i = 0; i < table.Length; ++i) { 
      temp = 0; 
      a = (ushort)(i << 8); 
      for(int j = 0; j < 8; ++j) { 
       if(((temp^a) & 0x8000) != 0) { 
        temp = (ushort)((temp << 1)^poly); 
       } else { 
        temp <<= 1; 
       } 
       a <<= 1; 
      } 
      table[i] = temp; 
     } 
    } 
} 

来源: http://sanity-free.org/133/crc_16_ccitt_in_csharp.html

+0

我的第一个答案的道歉,我点击了错误的网址,最终给你简单的CRC代码。 – Polynomial

+0

任何特别的原因,这是得到downvoted? – Polynomial

1

,如果你需要CRC CCITT 16克米特你需要下面的代码(从我的网站):

var crc16Kermit = new Crc16(Crc16Mode.CcittKermit); 
var checksum = crc16Kermit.ComputeChecksumBytes(0x01, 0x23, 0x45); 
// checksum = 0x2e, 0x46 

这里的源以上代码

using System; 

public enum Crc16Mode : ushort { Standard = 0xA001, CcittKermit = 0x8408 } 

public class Crc16 { 
    static ushort[] table = new ushort[256]; 

    public ushort ComputeChecksum(params byte[] bytes) { 
     ushort crc = 0; 
     for(int i = 0; i < bytes.Length; ++i) { 
      byte index = (byte)(crc^bytes[i]); 
      crc = (ushort)((crc >> 8)^table[index]); 
     } 
     return crc; 
    } 

    public byte[] ComputeChecksumBytes(params byte[] bytes) { 
     ushort crc = ComputeChecksum(bytes); 
     return BitConverter.GetBytes(crc); 
    } 

    public Crc16(Crc16Mode mode) { 
     ushort polynomial = (ushort)mode; 
     ushort value; 
     ushort temp; 
     for(ushort i = 0; i < table.Length; ++i) { 
      value = 0; 
      temp = i; 
      for(byte j = 0; j < 8; ++j) { 
       if(((value^temp) & 0x0001) != 0) { 
        value = (ushort)((value >> 1)^polynomial); 
       }else { 
        value >>= 1; 
       } 
       temp >>= 1; 
      } 
      table[i] = value; 
     } 
    } 
} 

上述代码的链接:http://sanity-free.org/147/standard_crc16_and_crc16_kermit_implementation_in_csharp.html