ZHCU873C june 2021 – july 2023 HDC3020 , HDC3020-Q1 , HDC3021 , HDC3021-Q1 , HDC3022 , HDC3022-Q1
以下代码片段描述了如何为 HDC3x 器件生成 C 语言的 8 位 CRC 代码。
#include <stdio.h>
unsigned char crcHDC3 (unsigned char msg[], int msglen) {
unsigned char crc = 0xFF;
for (int byte = 0; byte < msglen; byte++) {
crc ^= msg[byte];
for (int bit = 0; bit < 8; bit++) {
if (crc & 0x80)
crc = (crc << 1) ^ 0x31;
else
crc = (crc << 1);
}
}
return crc;
}
void main(int argc, char *argv[]) {
unsigned char msg[20];
int msglen = (argc > 1) ? (argc - 1) : 2;
msg[0] = 0xAB;
msg[1] = 0xCD;
for (int i = 1; i < argc; i++) {
sscanf(argv[i], "%X", &msg[i-1]);
}
printf("crc" 0x%X\n", crcHDC3(msg, msglen));
}