How do CRC algorithms work for CCITT16 and how to get one for CCITT8
Domanda
I'm looking to implement a CRC-8 checksum - and in reading up on CRC in general I came across this algorithm for CCITT-16 (polynomial X^16 + X^12 + X^5 + 1):
unsigned char ser_data;
static unsigned int crc;
crc = (unsigned char)(crc >> 8) | (crc << 8);
crc ^= ser_data;
crc ^= (unsigned char)(crc & 0xff) >> 4;
crc ^= (crc << 8) << 4;
crc ^= ((crc & 0xff) << 4) << 1;
Alternatively as a macro:
#define crc16(chk, byte) \
{ \
chk = (unsigned char) (chk >> 8) | (chk << 8); \
chk ^= byte; \
chk ^= (unsigned char)(chk & 0xFF) >> 4; \
chk ^= (chk << 8) << 4; \
chk ^= ((chk & 0xFF) << 4) << 1; \
}
I have two questions here:
- How is this algorithm derived from the polynomial?
- Is there a similar simple algorithm for CCITT8 (polynomial X^8 + X^2 + X + 1)?
Soluzione
Altri suggerimenti
Here is a C implementation of CRC8-CCITT based loosely on the code from this answer (https://stackoverflow.com/a/15171925/1628701):
uint8_t crc8_ccitt(uint8_t crc, const uint8_t *data, size_t dataLength){
static const uint8_t POLY = 0x07;
const uint8_t *end = data + dataLength;
while(data < end){
crc ^= *data++;
crc = crc & 0x80 ? (crc << 1) ^ POLY : crc << 1;
crc = crc & 0x80 ? (crc << 1) ^ POLY : crc << 1;
crc = crc & 0x80 ? (crc << 1) ^ POLY : crc << 1;
crc = crc & 0x80 ? (crc << 1) ^ POLY : crc << 1;
crc = crc & 0x80 ? (crc << 1) ^ POLY : crc << 1;
crc = crc & 0x80 ? (crc << 1) ^ POLY : crc << 1;
crc = crc & 0x80 ? (crc << 1) ^ POLY : crc << 1;
crc = crc & 0x80 ? (crc << 1) ^ POLY : crc << 1;
}
return crc;
}
this web page: https://decibel.ni.com/content/docs/DOC-11072 contains a link to a .zip file for each of the common (including the ones you ask for) algorithms for crc calculation.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow