为 C 中的某些字符计算 CRC16 时出错

Error calculating CRC16 for certain characters in C

我正在尝试使用此代码来计算 CRC16 绕过。对于常规字符,它可以工作,但对于像 0xA0 0x00 0x01 0x01 这样的十六进制序列,它会失败,不会返回正确的值。放宽我,平时我不写C代码

#include <stdio.h>
#include <string.h>

unsigned short CalculateCRC(unsigned char* a_szBuffuer, short a_sBufferLen){
    unsigned short usCRC = 0;
    for (short j = 0; j < a_sBufferLen; j++)
    {
    unsigned char* pucPtr = (unsigned char *)&usCRC;
    *(pucPtr + 1) = *(pucPtr + 1) ^ *a_szBuffuer++;
    for (short i = 0; i <= 7; i++)
    {
    if (usCRC & ((unsigned short) 0x8000))
    {
    usCRC = usCRC << 1;
    usCRC = usCRC ^ ((unsigned short) 0x8005);
    }
    else
    usCRC = usCRC << 1;
    }
    }
    return (usCRC);
}

void append(char* s, char c)
{
        int len = strlen(s);
        s[len] = c;
        s[len+1] = '[=10=]';
}

int main() {

   char d = (char)0xA0;
   char d1 = (char)0x00;
   char d2 = (char)0x01;
   char d3 = (char)0x01;
   char sss[256]="";

   append(sss, d);
   append(sss, d1);
   append(sss, d2);
   append(sss, d3);
   unsigned char* uCB1 = (unsigned char*)sss;
   unsigned short CRC= CalculateCRC(uCB1,4);

   printf("CRC = %i\n", CRC);
   printf("%s\n", sss);
   printf("%x\n", CRC);
}

strlen(s); 用于查找 stringlength,而不是查找字符数组的长度使用,特别是如果它可能包含 '[=12=]'

代码需要跟踪与另一个变量一起使用的数组大小。

// void append(char* s, char c) {
void append(char* s, size_t *sz, char c) {
  s[*sz] = c;
  (*sz)++;
}

...
size_t size = 0;
append(sss, &size, d);
append(sss, &size, d1);
append(sss, &size, d2);
append(sss, &size, d3);
unsigned char* uCB1 = (unsigned char*)sss;
unsigned short CRC= CalculateCRC(uCB1, size);

// printf("%s\n", sss);
write a loop to print each `sss[]`.