Algorithm CRC-12

*爱你&永不变心* 提交于 2019-12-10 19:34:39

问题


I am trying to do crc_table for 12-bit CRC and the algorithm, but always I got wrong results.

Can you help me? To create crc table I try:

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;
    }

}

I updated that and CRC algorithm is:

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);

}

But It isn't working.....


回答1:


This doesn't seem right:

if (remainder & 10000000)

It looks like you are intending this number to be binary, but it is actually decimal. You should use a hex literal instead (0x80).

There also seem to be problems with this number, and with the size of the shift you do: This test should check if the high-order bit of the remainder is set. Since you are doing a 12-bit CRC, the mask should be 0x800 (binary 100000000000). And the shift above that should probably be:

remainder = dividend << 4;

to set the leftmost 8 bits of the remainder.




回答2:


The Boost library would have a CRC checksum algorithm already implemented, which can be used with different polynomials for division and numbers of bits. Use this link for further informations Boost CRC.

An example implementation of myself would be:

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();

To use a CRC with 12 bits you have to adopt the number of bits and the used polynomial, which can be found here: Wikipedia CRC polynomials



来源:https://stackoverflow.com/questions/12632051/algorithm-crc-12

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!