Calculate checksum(hex) of string with ASCII(unsigned int). Use to detected communication error.
CheckSum.cpp@0:b3a521e42246, 2015-10-21 (annotated)
- Committer:
- AkinoriHashimoto
- Date:
- Wed Oct 21 02:10:40 2015 +0000
- Revision:
- 0:b3a521e42246
1st publish.
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
AkinoriHashimoto | 0:b3a521e42246 | 1 | #include "CheckSum.h" |
AkinoriHashimoto | 0:b3a521e42246 | 2 | |
AkinoriHashimoto | 0:b3a521e42246 | 3 | |
AkinoriHashimoto | 0:b3a521e42246 | 4 | string CheckSum::calc(string str, int Byte) |
AkinoriHashimoto | 0:b3a521e42246 | 5 | { |
AkinoriHashimoto | 0:b3a521e42246 | 6 | // calculate SUM. |
AkinoriHashimoto | 0:b3a521e42246 | 7 | int sum= 0; |
AkinoriHashimoto | 0:b3a521e42246 | 8 | int size= str.size(); |
AkinoriHashimoto | 0:b3a521e42246 | 9 | |
AkinoriHashimoto | 0:b3a521e42246 | 10 | for(int idx= 0; idx < size; idx++) |
AkinoriHashimoto | 0:b3a521e42246 | 11 | sum += str[idx]; |
AkinoriHashimoto | 0:b3a521e42246 | 12 | |
AkinoriHashimoto | 0:b3a521e42246 | 13 | // convert HEX. REWRITE/REUSE. |
AkinoriHashimoto | 0:b3a521e42246 | 14 | str= I2A(sum, 16, (Byte* 2)); // Hex, over 2chars(ex. 0x0f). |
AkinoriHashimoto | 0:b3a521e42246 | 15 | |
AkinoriHashimoto | 0:b3a521e42246 | 16 | // N[B] with the end of the hex checksum. |
AkinoriHashimoto | 0:b3a521e42246 | 17 | size= str.size(); |
AkinoriHashimoto | 0:b3a521e42246 | 18 | if(size > (Byte* 2)) // cut tail from str. |
AkinoriHashimoto | 0:b3a521e42246 | 19 | return str.substr(size- (Byte* 2)); |
AkinoriHashimoto | 0:b3a521e42246 | 20 | |
AkinoriHashimoto | 0:b3a521e42246 | 21 | if(size == (Byte* 2)) // return |
AkinoriHashimoto | 0:b3a521e42246 | 22 | return str; |
AkinoriHashimoto | 0:b3a521e42246 | 23 | |
AkinoriHashimoto | 0:b3a521e42246 | 24 | // size < Byte |
AkinoriHashimoto | 0:b3a521e42246 | 25 | return "ERR"; |
AkinoriHashimoto | 0:b3a521e42246 | 26 | } |
AkinoriHashimoto | 0:b3a521e42246 | 27 | |
AkinoriHashimoto | 0:b3a521e42246 | 28 | bool CheckSum::compare(string str, string sum) |
AkinoriHashimoto | 0:b3a521e42246 | 29 | { |
AkinoriHashimoto | 0:b3a521e42246 | 30 | int Byte= sum.size()/ 2; |
AkinoriHashimoto | 0:b3a521e42246 | 31 | return strCompareComplete(CheckSum::calc(str, Byte), sum); |
AkinoriHashimoto | 0:b3a521e42246 | 32 | } |
AkinoriHashimoto | 0:b3a521e42246 | 33 | |
AkinoriHashimoto | 0:b3a521e42246 | 34 | // EOF |