Question

can someone please explain what this code is doing? i have to interpret this code and use it as a checksum code, but i am not sure if it is absolutely correct. Especially how the overflows are working and what *cp, const char* cp and sum & 0xFFFF mean? The basic idea was to take an input as string from user, convert it to binary form 16 bits at a time. Then sum all the multiple 16 bits together (in binary) and get a 16 bit sum. If there is any overflow bit in the addition, add that to lsb of final sum. Then take a ones complement of the result.

How close is this code to doing the above?

 unsigned int packet::calculateChecksum()

{   
unsigned int c = 0;
int i;
string j;
int k;
cout<< "enter a message" << message; 
getline(cin, message) ; // Some string.
//std::string message = 
std::vector<uint16_t> bitvec;
const char* cp = message.c_str()+1;
while (*cp) {
   uint16_t bits = *(cp-1)>>8 + *(cp);
   bitvec.push_back(bits);
   cp += 2; 
 }

uint32_t sum=0;
uint16_t overflow=0;
uint32_t finalsum =0; 

// Compute the sum.  Let overflows accumulate in upper 16 bits.
for(auto j = bitvec.begin(); j != bitvec.end(); ++j) 
    sum += *j;

// Now fold the overflows into the lower 16 bits.  Loop until no overflows.
do {
  sum = (sum & 0xFFFF) + (sum >> 16);
  } while (sum > 0xFFFF);

// Return the 1s complement sum in finalsum
finalsum = 0xFFFF & sum; 

    //cout<< "the finalsum is" << c;
        c = finalsum;
        return c;

    }
Était-ce utile?

La solution

I see several issues in the code:

  1. cp is a pointer to zero ended char array holding the input message. The while(*cp) will have problem as inside the while loop body cp is incremented by 2!!! So it's fairly easy to skip the ending \0 of the char array (e.g. the input message has 2 characters) and result in a segmentation fault.
  2. *(cp) and *(cp-1) fetch the two neighbouring characters (bytes) in the input message. But why the two-bytes word is formed by *(cp-1)>>8 + *(cp)? I think it would make sense to formed the 16bits word by *(cp-1)<<8 + *(cp) i.e. the preceding character sits on the higher byte and the following character sits on the lower byte of the 16bits word.

To answer your question sum & 0xFFFF just means calculating a number where the higher 16 bits are zero and the lower 16 bits are the same as in sum. the 0xFFFF is a bit mask.

The funny thing is, even the above code might not doing the exact thing you mentioned as requirement, as long as the sending and receiving party are using the same piece of incorrect code, your checksum creation and verification will pass, as both ends are consistent with each other:)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top