CRC CODE
Fri Nov 15 2024 17:52:16 GMT+0000 (Coordinated Universal Time)
Saved by @coding1
include <stdio.h>
#include <string.h>
#define MAX_LEN 28
char t[MAX_LEN], cs[MAX_LEN], g[MAX_LEN];
int a, e, c, b;
void xor() {
for (c = 1; c < strlen(g); c++)
cs[c] = ((cs[c] == g[c]) ? '0' : '1');
}
void crc() {
for (e = 0; e < strlen(g); e++)
cs[e] = t[e];
do {
if (cs[0] == '1') {
xor();
}
for (c = 0; c < strlen(g) - 1; c++)
cs[c] = cs[c + 1];
cs[c] = t[e++];
} while (e <= a + strlen(g) - 1);
}
int main() {
int flag = 0;
do {
printf("\n1. CRC-12\n2. CRC-16\n3. CRC-CCITT\n4. Exit\n\nEnter your option: ");
scanf("%d", &b);
switch (b) {
case 1:
strcpy(g, "1100000001111");
break;
case 2:
strcpy(g, "11000000000000101");
break;
case 3:
strcpy(g, "10001000000100001");
break;
case 4:
return 0;
default:
printf("Invalid option. Please try again.\n");
continue;
}
printf("\nEnter data: ");
scanf("%s", t);
printf("\n-----------------------\n");
printf("Generating polynomial: %s\n", g);
a = strlen(t);
// Append zeros to the data
for (e = a; e < a + strlen(g) - 1; e++)
t[e] = '0';
t[e] = '\0'; // Null terminate the string
printf("--------------------------\n");
printf("Modified data is: %s\n", t);
printf("-----------------------\n");
crc();
printf("Checksum is: %s\n", cs);
// Prepare the final codeword
for (e = a; e < a + strlen(g) - 1; e++)
t[e] = cs[e - a];
printf("-----------------------\n");
printf("Final codeword is: %s\n", t);
printf("------------------------\n");
// Error detection option
printf("Test error detection (0: yes, 1: no)?: ");
scanf("%d", &e);
if (e == 0) {
do {
printf("\n\tEnter the position where error is to be inserted: ");
scanf("%d", &e);
} while (e <= 0 || e > a + strlen(g) - 1);
t[e - 1] = (t[e - 1] == '0') ? '1' : '0'; // Toggle the bit
printf("-----------------------\n");
printf("\nErroneous data: %s\n", t);
}
crc();
for (e = 0; (e < strlen(g) - 1) && (cs[e] != '1'); e++);
if (e < strlen(g) - 1)
printf("Error detected\n\n");
else
printf("No error detected\n\n");
printf("-----------------------\n");
} while (flag != 1);
return 0;
}



Comments