Question

I need some help understanding the follow bit of code, and where I might be going wrong. Using MPLAB

This is the beginning of the function, i get this part

char validateNemaSentence(char *pSentence)
{
    char chkSumToken[3];
    unsigned char calculatedChecksum = 0;
    char errorCode = NOERROR;

    if(*pSentence != '$')
      return ERROR;
      pSentence++;

This next portion is where i have troubles

while (*pSentence != '\0' && *pSentence != '*')
    {
    calculatedChecksum ^= *pSentence;
    pSentence++;
}

This part of the function increments the address of pSentence, which is is brought in by the function as an array. this array is actually made up of a string of user inputs that is supposed to be "parsed" and evaluated with a checkSum. This while loop goes through each element in the array, as long as it doesn't see a NULL or an ASTERIX, and Xors the value. So if i were to say that the element[1] and element [2] of pSentence were say "A" and "B" (so the while loop, loops twice, and checkSum is Xor the value "A"), then do i Xor their ascii values together to get a value for checksum? Is that how that part of the function works?

So A ascii is 0x41 B ascii is 0x42

calculatedChecksum ^= *pSentence (which is A) 

= 0100 0001

and then

calculatedChecksum ^= *Sentence (which is B)

0100 0001 (Current value of calcChecksum)

0100 0010 (ASCII of B)

= 0000 0011

Is that correct?

Now this last function is where most of my problem is. My code always returns ERROR, and I am not sure how to properly assign a checksum for the functions,because if i change the strcmp below to "== 0" then i can actually send a pSentence through and evaluate it, but then my checksum won't be working properly

if(*pSentence == '*')
    {
    sprintf(chkSumToken, "%2x", calculatedChecksum);
    pSentence++;    
    if(strcmp(pSentence,chkSumToken) !=0) errorCode = ERROR;
    }
Was it helpful?

Solution

I think your problem is, that your expectation about the output from sprintf() is wrong. To see what's wrong, just add this line before the condition with the strcmp() call:

fprintf(stderr, "chkSumToken: \"%s\"\npSentence: \"%s\"\n", chkSumToken, pSentence);

I think, the output that you expect is for example "03", but sprintf() pads fields with spaces by default, delivering " 3" instead. To get a leading zero, use "%02x" as the format string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top