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

Dependencies:   StrLib

CheckSum.h

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

File content as of revision 0:b3a521e42246:

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

/** @code
 #include "mbed.h"
#include "CheckSum.h"

DigitalOut led[]= {LED1, LED2, LED3, LED4};
Serial pc(USBTX, USBRX);
int main()
{
    string str, tmp, checksum;
    str= "";
    int idx;
    bool ans;
    while(true) {
        led[0]= !led[0];
        if(pc.readable())
            str += pc.getLine();
        idx= str.find("\r\n");
        if(idx != string::npos) {
            led[1]= !led[1];
            tmp= str.substr(0, idx);
            str= str.substr(idx+ 2);

            checksum= CheckSum::calc(tmp);
            ans= CheckSum::compare(tmp, checksum);
            pc.printf("%s\t%s.\r\n", tmp.c_str(), checksum.c_str());
            if(ans)
                pc.printf("TRUE");
            for(int i= 1; i < 5; i++) {
                checksum= CheckSum::calc(tmp, i);
                ans= CheckSum::compare(tmp, checksum);
                pc.printf("%s\t%s.\r\n", tmp.c_str(), checksum.c_str());
                if(ans)
                    pc.printf("TRUE");
            }
        }
    }
}
 @endcode
 */

#pragma once
#include "mbed.h"

#include "StrLib.h"

class CheckSum
{
public:
    /** Create checksum (hex).
     *  @param; str:  target
     *          Byte: returnend string size[B].
     *  @return; The end of hex checksum.
     */
    static string calc(string str, int Byte= 1);
    
    /** Compare Check.
     *  @param; str: target.
     *          sum: checksum of target.
     *  @return; true or false.
     *          if target equals to sum, returned true.
     *          else, returned false.
     */
    static bool compare(string str, string sum);
};

// EOF