網際校正和演算法實現 佟強 2008.10.20
原理請參考:
網際校正和演算法: http://blog.csdn.net/microtong/archive/2008/10/20/3112139.aspx
網際校正和演算法的特徵:http://blog.csdn.net/microtong/archive/2008/10/20/3112157.aspx
- /*
- 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);
- }