0%

Calculate the checksum of a string by C/C++

Calculate the checksum of the string by C/C++, source code sharing 💟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "stdio.h"

int main() {
char msg[] = "5ABA440A4F5A2D46511664726976654368616E676510697320746F6B656E0C78B3B9121E81";
char buf[255];

strcpy(buf, msg);
unsigned char checksum = 0;
int i = 0;
for(i = 0; i < strlen(msg); i++) {
if(buf[i] < ':'){
checksum = checksum + buf[i] - '0';
printf("buf[%d]:%d\n",i, buf[i] - '0');
} else {
checksum = checksum + buf[i] - 'A' + 10;
printf("buf[%d]:%d\n",i, buf[i] - 'A' + 10);
}
}

printf("checksum:%d",checksum);
return 0;
}

Only uppercase characters and numbers are supported. You can support other characters.


After reading the ASCII table, you will understand the principle. 🚩

DEC OCT HEX BIN Symbol
48 060 30 00110000 0
49 061 31 00110001 1
50 062 32 00110010 2
51 063 33 00110011 3
52 064 34 00110100 4
53 065 35 00110101 5
54 066 36 00110110 6
55 067 37 00110111 7
56 070 38 00111000 8
57 071 39 00111001 9
58 072 3A 00111010 :