/*
pBuffer是要校验的数据报开始地址
nSize指定校验内容长度,单位是字节
*/
unsigned short checksum_calculating(unsigned short *pBuffer, int nSize)
{
unsigned long dwCksum = 0; // 32位累加和
unsigned char* p=(unsigned char*)&dwCksum;
// 以两字节为单位反复累加
while(nSize > 1)
{
dwCksum += *pBuffer++;
printf("\t\t%.2x %.2x %.2x %.2x\n",*p,*(p+1),*(p+2),*(p+3));
nSize -= sizeof(unsigned short);
}
printf("\t\t%.2x %.2x %.2x %.2x\n",*p,*(p+1),*(p+2),*(p+3));
// 如果总字节数为奇数则加上最后一个字节
if (nSize)
{
dwCksum += *(unsigned char*) pBuffer;
printf("\t\t%.2x %.2x %.2x %.2x\n",*p,*(p+1),*(p+2),*(p+3));
}
//把32位整数高位中的进位累加到低16位
while(dwCksum>>16){
dwCksum = (dwCksum&0xffff) + (dwCksum>>16);
printf("\t\t%.2x %.2x %.2x %.2x\n",*p,*(p+1),*(p+2),*(p+3));
}
//取反得到校验和
dwCksum = ~dwCksum;
printf("\t\t%.2x %.2x %.2x %.2x\n",*p,*(p+1),*(p+2),*(p+3));
// 返回16位校验和
return (unsigned short) (dwCksum);
} 来源:教育联展网-软件水平考试