CRC Method Using C
CRC Method Using C
#include<stdio.h>
#include<string.h>
#define MAX_LEN 50 // Max length for data and polynomial
// Length of the generator polynomial
int N;
// Data to be transmitted and received
char data[MAX_LEN];
char check_value[MAX_LEN];
// Generator polynomial
char gen_poly[MAX_LEN];
// Function that performs XOR operation
void XOR() {
// If both bits are the same, the output is 0; if the bits are different, the output is 1
for (int j = 0; j < N; j++) {
check_value[j] = (check_value[j] == gen_poly[j]) ? '0' : '1';
}
}
// Function to perform CRC calculation (sender-side)
void crc() {
int data_len = strlen(data); // Length of the data
int i, j;
// Initializing check_value with data (append N-1 zeros to the end of the data)
for (i = 0; i < data_len; i++) {
check_value[i] = data[i];
}
for (i = data_len; i < data_len + N - 1; i++) {
check_value[i] = '0';
}
// Perform CRC calculation
for (i = 0; i < data_len; i++) {
if (check_value[i] == '1') { // If the current bit is 1, XOR with the generator polynomial
for (j = 0; j < N; j++) {
check_value[i + j] = (check_value[i + j] == gen_poly[j]) ? '0' : '1';
}
}
}
// Now, check_value contains the original data and CRC appended together
printf("CRC codeword: ");
for (i = 0; i < data_len; i++) {
printf("%c", data[i]);
}
for (i = data_len; i < data_len + N - 1; i++) {
printf("%c", check_value[i]);
}
printf("\n");
}
// Function to check if the CRC is valid at receiver side
int check_crc(char received_data[], char gen_poly[]) {
int data_len = strlen(received_data); // Length of the received data
int i, j;
// Initialize check_value with the received data
for (i = 0; i < data_len; i++) {
check_value[i] = received_data[i];
}
// Perform CRC check
for (i = 0; i < data_len - N + 1; i++) {
if (check_value[i] == '1') { // If the current bit is 1, XOR with the generator polynomial
for (j = 0; j < N; j++) {
check_value[i + j] = (check_value[i + j] == gen_poly[j]) ? '0' : '1';
}
}
}