Function to Calculate a CRC16 Checksum

前端 未结 7 1326
走了就别回头了
走了就别回头了 2020-12-04 10:19

I\'m working on a library to provide simple reliable communication over an RS232 or RS485 connection. Part of this code involves using a CRC16 checksum on the data to detec

相关标签:
7条回答
  • 2020-12-04 10:55

    Here follows a working code to calculate crc16 CCITT. I tested it and the results matched with those provided by http://www.lammertbies.nl/comm/info/crc-calculation.html.

    unsigned short crc16(const unsigned char* data_p, unsigned char length){
        unsigned char x;
        unsigned short crc = 0xFFFF;
    
        while (length--){
            x = crc >> 8 ^ *data_p++;
            x ^= x>>4;
            crc = (crc << 8) ^ ((unsigned short)(x << 12)) ^ ((unsigned short)(x <<5)) ^ ((unsigned short)x);
        }
        return crc;
    }
    
    0 讨论(0)
提交回复
热议问题