checksum 算法
程序员文章站
2022-07-10 14:33:33
...
一组数据 test[11]={0x55,0x36,0xdc,0x3d,0x36, 0x33,0x8f,0x30,0x31,0x33, 0xd0}; 求其和校验:前10个数之和 + 校验字节(test[10]) = 0 ,依次可求得checksum ,代码如下:
#include <stdio.h>
#include <string.h>
//typedef unsigned char U8
//typedef unsigned short U16
/*
U8 CalChecksum(U8 *dat)
{
U16 i;
U8 sum=0,checksum=0;
for(i=0;i<128;i++){
sum +=dat[i];
}
sum =~sum;
checksum = (U8)((sum+1)&0xff);
printf("checksum:%x ",checksum);
return checksum;
}
U8 CalSum(U8 *dat)
{
U16 i;
U8 sum=0,checksum=0;
U16 len = sizeof(dat);
printf("len:%x ",len);
for(i=0;i<len;i++){
sum +=dat[i];
}
printf("sum:%x ",sum);
}
*/
unsigned char CalChecksum1(unsigned char *dat,unsigned short len)
{
unsigned short i;
unsigned char sum=0,checksum=0;
//unsigned short len = strlen(dat);
printf("CalChecksum len:%x \n",sizeof(dat));
for(i=0;i<len-1;i++){
printf("dat[%d]=%x\n",i,dat[i]);
sum +=dat[i];
}
printf("---sum:%x \n",sum);
sum =~sum;
checksum = (unsigned char)((sum+1)&0xff);
printf("checksum:%x \n",checksum);
return checksum;
}
unsigned char CalChecksum2(unsigned char *dat,unsigned short len)
{
unsigned short i;
unsigned char sum=0,checksum=0;
//unsigned short len = strlen(dat);//sizeof(dat);
printf("CalSum len:%x \n",sizeof(dat));//4 指针dat本身大小 4字节
printf("CalSum len:%x \n",strlen(dat));//10
printf("len:%x \n",len);
for(i=0;i<len-1;i++){
printf("dat[%d]=%x\n",i,dat[i]);
sum +=dat[i];
}
checksum = 0x100 - sum;
return checksum;
printf(">>>sum:%x \n checksum:%x \n",sum,checksum);
}
int main(void)
{
unsigned char test[11]={0x55,0x36,0xdc,0x3d,0x36, 0x33,0x8f,0x30,0x31,0x33, 0x60};
unsigned char res[128]={0};
printf("test len:%x \n",sizeof(test));
CalChecksum2(test,sizeof(test));
CalChecksum1(test,sizeof(test));
}