Sie sind auf Seite 1von 3

Checksum Algorithm

1. Take 2 binary input strings.


2. Do their binary sum to find out the checksum which will be sent to the destination
or to the receiver.
3. In binary sum there are 6 cases:-
a. If both bits are 0 and carry is 0, sum=0 and carry=0
b. If both bits are 0 and carry is 1,sum=1 and carry=0
c. If both bits are 1 and carry is 0,sum=0 and carry=1
d. If both bits are 1 and carry is 1,sum=1 and carry=1
e. If either bit is 1 and carry is 0,sum=1 and carry=0
f. If either bit is 1 and carry is 1,sum=0 and carry=1
4. While doing the addition we have to add the binary strings from rightmost end i.e
LSB to MSB.
5. When binary sum is done 1’s complement of it is taken by reversing 1’s to 0’s and
vice versa.
6. The resulting 1’s complement is the Checksum.
7. Stop.

Checksum Program in C

1 #include<stdio.h>
2 #include<string.h>
3 int main()
4 {
5 char a[20],b[20];
6 char sum[20],complement[20];
7 int i,length;
8 printf("Enter first binary string\n");
9 scanf("%s",&a);
10 printf("Enter second binary string\n");
11 scanf("%s",&b);
12 if(strlen(a)==strlen(b)){
13 length = strlen(a);
14 char carry='0';
15 for(i=length-1;i>=0;i--)
16 {
17 if(a[i]=='0' && b[i]=='0' && carry=='0')
18 {
19 sum[i]='0';
20 carry='0';
21 }
22 else if(a[i]=='0' && b[i]=='0' && carry=='1')
23 {
24 sum[i]='1';
25 carry='0';
26 }
27 else if(a[i]=='0' && b[i]=='1' && carry=='0')
28 {
29 sum[i]='1';
30 carry='0';
31 }
32 else if(a[i]=='0' && b[i]=='1' && carry=='1')
33 {
34 sum[i]='0';
35 carry='1';
36 }
37 else if(a[i]=='1' && b[i]=='0' && carry=='0')
38 {
39 sum[i]='1';
40 carry='0';
41 }
42 else if(a[i]=='1' && b[i]=='0' && carry=='1')
43 {
44 sum[i]='0';
45 carry='1';
46 }
47 else if(a[i]=='1' && b[i]=='1' && carry=='0')
48 {
49 sum[i]='0';
50 carry='1';
51 }
52 else if(a[i]=='1' && b[i]=='1' && carry=='1')
53 {
54 sum[i]='1';
55 carry='1';
56 }
57 else
58 break;
59 }
60 printf("\nSum=%c%s",carry,sum);
61 for(i=0;i<length;i++)
62 {
63 if(sum[i]=='0')
64 complement[i]='1';
65 else
66 complement[i]='0';
67 }
68 if(carry=='1')
69 carry='0';
70 else
71 carry='1';
72 printf("\nChecksum=%c%s",carry,complement);
73 }
74 else {
75 printf("\nWrong input strings");
76 }
77 }

Das könnte Ihnen auch gefallen