2012-09-28 69 views
3

我試圖做crc_table 12位CRC校驗和算法,但總是我得到錯誤的結果。算法CRC-12

你能幫我嗎?要創建CRC表我嘗試:

void crcInit(void) 
{ 
    unsigned short remainder; 
    int dividend; 
    unsigned char bit; 

    for (dividend = 0; dividend < 256; ++dividend) 
    { 
     remainder = dividend << 4; 

     for (bit = 8; bit > 0; --bit) 
     { 
      if (remainder & 0x800) 
      { 
       remainder = (remainder << 1)^0x180D; //Polynomio of CRC-12 
      } 
      else 
      { 
       remainder = (remainder << 1); 
      } 
     } 
     crcTable[dividend] = remainder; 
    } 

} 

我更新了與CRC算法是:

unsigned short crcFast(unsigned char const message[], int nBytes) 
{ 
    unsigned short remainder = 0x0000; 
    unsigned char data; 
    int byte; 


    /* 
    * Divide the message by the polynomial, a byte at a time. 
    */ 
    for (byte = 0; byte < nBytes; ++byte) 
    { 
     data = message[byte]^(remainder >> 4); 
    remainder = crcTable[data]^(remainder << 8); 
    } 

    /* 
    * The final remainder is the CRC. 
    */ 
    return (remainder^0); 

} 

,但它不工作.....

+0

是這來自UIUC CS438 MP1?我在同一班。 :) – Mysticial

+0

請記住,有三種算法自稱爲CRC-12。所以要確保你正在爲你的目的實施正確的。其他常見多項式是:0x180B和0x180F。同時檢查初始值和最終異或值。 –

回答

3

這看起來不正確:

if (remainder & 10000000) 

它看起來像你打算這個數字是二進制的,但它實際上是十進制的。您應該使用十六進制文字(0x80)。

也有似乎是這個數字的問題,並與你做的移位大小:如果餘數的高階位設置這個測試應該檢查。由於你正在做一個12位的CRC,掩碼應該是0x800(二進制100000000000)。並且上面的轉換應該可能是:

remainder = dividend << 4; 

設置剩下的最左邊的8位。

1

Boost庫就已經實現CRC校驗算法,它可以與分工不同多項式和的位數來使用。 使用此鏈接瞭解更多信息Boost CRC

自己的示例實現是:

string data = "S95I"; 
boost::crc_optimal<11, 0x571> crc; 
crc.process_bytes(data.data(), data.size()); 
stringstream checksum; 
checksum << (int)crc() % 1296; 
string resultCheck = checksum.str(); 

要使用兒童權利委員會12位,你必須採取的比特數和使用多項式,它可以在這裏找到:Wikipedia CRC polynomials