Checksum calculation

To calculate CRC I found a piece of code but I don't understand the concept. Here is the code:

count =128 and ptr=some value;

      

calcrc(unsigned char *ptr, int count)
{
    unsigned short  crc;
    unsigned char i;

    crc = 0;

    while (--count >= 0)
    {
        crc = crc ^ (unsigned short)*ptr++ << 8;
        i = 8;
        do
        {
            if (crc & 0x8000)
                crc = crc << 1 ^ 0x1021;
            else
                crc = crc << 1;
        } while(--i);
    }
    return (crc);
}

      

Please explain to me and explain the logic to me.

+1


a source to share


4 answers


It looks like a CRC (in particular, it looks like CRC-16-CCITT, used by things like 802.15.4, X.25, V.41, CDMA, Bluetooth, XMODEM, HDLC, PPP, and IrDA). You might want to check out CRC theory on the Wikipedia linked page to gain a deeper understanding. Or you can think of it as a "black box" that simply solves the problem of calculating the checksum.



+4


a source


You probably need to know that in C, the ^ operator is a bitwise XOR operator and the <operator is a left shift operator (equivalent to multiplying by 2 by the cardinality of the number to the right of the operator). Also, the expression crc and 0x8000 tests the most significant bit of the crc variable set. This will help you work out a low level explanation of what happens when it works, for a high level explanation of what a CRC is and why you might need it, read the Wikipedia Page or How the stuff works .



+3


a source


One famous text on CRC is Ross Williams ' Painless Guide to CRC Error Detection Algorithms . It takes a while to learn, but it's pretty thorough.

+3


a source


Take a look at my answer to How can I guess the checksum algorithm?

+1


a source







All Articles