Calculate checksum(hex) of string with ASCII(unsigned int). Use to detected communication error.

Dependencies:   StrLib

CheckSum.cpp

Committer:
AkinoriHashimoto
Date:
2015-10-21
Revision:
0:b3a521e42246

File content as of revision 0:b3a521e42246:

#include "CheckSum.h"


string CheckSum::calc(string str, int Byte)
{
    // calculate SUM.
    int sum= 0;
    int size= str.size();

    for(int idx= 0; idx < size; idx++)
        sum += str[idx];

    // convert HEX. REWRITE/REUSE.
    str= I2A(sum, 16, (Byte* 2)); // Hex, over 2chars(ex. 0x0f).

    // N[B] with the end of the hex checksum.
    size= str.size();
    if(size > (Byte* 2))        // cut tail from str.
        return str.substr(size- (Byte* 2));

    if(size == (Byte* 2))    // return 
        return str;
        
    // size < Byte
    return "ERR";
}

bool CheckSum::compare(string str, string sum)
{
    int Byte= sum.size()/ 2;
    return strCompareComplete(CheckSum::calc(str, Byte), sum);
}

// EOF