cksum
#include <iostream>
using std::cout ;
using std::endl ;
static const int _ONE_ = 1 ;
#define isNetworkByteOrderCPU() (*((char*)(&_ONE_)) == 0)
unsigned short cksum(
unsigned short* buf,
unsigned int nBytes,
unsigned short sum0 = 0
){
unsigned long sum = 0 ;
if (nBytes & 1) {
sum = ((unsigned char*)buf)[nBytes-1] ;
if (isNetworkByteOrderCPU()){
sum <<= 8 ;
}
nBytes-- ;
}
sum += sum0 ;
unsigned int nWords = nBytes / 2 ;
while(nWords--){
sum += *buf++ ;
}
sum = (sum >> 16) + (sum & 0xffff) ;
sum = (sum >> 16) + (sum & 0xffff) ;
return ~sum ;
}
#define BufSize 1024
char buf[2+BufSize] ;
int main(void){
int i = 0 ;
for (i=2 ; i<2+BufSize ; i++){
buf[i] = i-2 ;
}
unsigned short checkSum = 0 ;
*(unsigned short*)buf = 0 ;
checkSum = cksum((unsigned short*)buf, 2+BufSize) ;
*(unsigned short*)buf = checkSum ;
checkSum = cksum((unsigned short*)buf, 2+BufSize) ;
if (checkSum != 0){
cout <<
"NG : i=" << (void*)i <<
", checkSum =" << (void*)checkSum <<
endl ;
}
if (checkSum == 0){
cout << "OK" << endl ;
}
return 0 ;
}