C program of Cyclic Redundancy Check
C program of Cyclic Redundancy Check
Program
#include<stdio.h>
// shorthand for loops
#define forn(i,e) for(int i = 0; i < e; i++)
#define forsn(i,s,e) for(int i = s; i < e; i++)
int validate_data(int len_data, int data[], int len_divisor, int divisor[]){
// Returns 1, if the data is correct
// Returns 0, if the data is incorrect/corrupted.
int current_bits[len_divisor];
forn(i, len_divisor) { current_bits[i] = data[i]; }
// the logic is same as generating the crc.
forn(i, len_data) {
if (!current_bits[0]) {
forn(j, len_divisor-1) { current_bits[j] = current_bits[j+1]; }
current_bits[len_divisor-1] = data[i+len_divisor];
} else {
forn(j, len_divisor) { current_bits[j] = current_bits[j]^divisor[j]; }
forn(j, len_divisor-1) { current_bits[j] = current_bits[j+1]; }
current_bits[len_divisor-1] = data[i+len_divisor];
}
}
// if all the bits upto length len_divisor-1 is 0, return 1, else return 0;
forn(i, len_divisor-1) { if(current_bits[i]) return 0; }
return 1;
}
int main(){
int len_divisor=0, len_data=0, len_data_and_pad=0;
printf("Enter the length of divisor > ");
scanf("%d",&len_divisor);
printf("Enter the length of data > ");
scanf("%d",&len_data);
// total length of data with padded CRC bits
len_data_and_pad = len_data+len_divisor-1;
int divisor[len_divisor], data[len_data_and_pad];
printf("\nEnter the divisor :- \n");
forn(i,len_divisor) { printf("> "); scanf("%d",&divisor[i]); }
printf("\nEnter the data :- \n");
forn(i,len_data) { printf("> "); scanf("%d",&data[i]); }
// initialize paddings with zero
forsn(i, len_data,len_data+len_divisor) { data[i] = 0; }
int current_bits[len_divisor];
forn(i, len_divisor) { current_bits[i] = data[i]; }
forn(i, len_data) {
// if first bit is zero, bits shift left by one place
// new bit is added at the end from the data bits.
if (!current_bits[0]) {
forn(j, len_divisor-1) { current_bits[j] = current_bits[j+1]; }
current_bits[len_divisor-1] = data[i+len_divisor];
} else {
// XOR current bits with divisor.
forn(j, len_divisor) { current_bits[j] = current_bits[j]^divisor[j]; }
forn(j, len_divisor-1) { current_bits[j] = current_bits[j+1]; }
current_bits[len_divisor-1] = data[i+len_divisor];
}
}
// replace padded data bits with the CRC available in current_bits[0:-2]
forsn(i, len_data, len_data_and_pad) { data[i] = current_bits[i-len_data]; }
printf("DATA > ");
forn(i, len_data_and_pad) { printf("%d ", data[i]); }
printf("\nCRC > ");
forn(i, len_divisor-1) { printf("%d ", current_bits[i]); }
// Receiver side...
int check = validate_data(len_data, data, len_divisor, divisor);
if (check){
printf("\n\nThe data is correct.\n");
} else {
printf("\n\nThe data is corrupted !!\n");
}
return 0;
}
Comments
Post a Comment
Give your feedback!
DO NOT SPAM !!
NO THIRD PARTY PROMOTIONAL LINK !!!! (else comment will be deleted.)