C Program for error detecting code using CRC-CCITT (16bit)

How to write a C Program for error detecting code using CRC-CCITT (16bit) in C Programming Language ?


Solution:

  1. #include<stdio.h>
  2. char m[50],g[50],r[50],q[50],temp[50];
  3. void caltrans(int);
  4. void crc(int);
  5. void calram();
  6. void shiftl();
  7. int main()
  8. {
  9. int n,i=0;
  10. char ch,flag=0;
  11. printf("Enter the frame bits:");
  12. while((ch=getc(stdin))!='\n')
  13. m[i++]=ch;
  14. n=i;
  15. for(i=0;i<16;i++)
  16. m[n++]='0';
  17. m[n]='\0';
  18. printf("Message after appending 16 zeros:%s",m);
  19. for(i=0;i<=16;i++)
  20. g[i]='0';
  21. g[0]=g[4]=g[11]=g[16]='1';g[17]='\0';
  22. printf("\ngenerator:%s\n",g);
  23. crc(n);
  24. printf("\n\nquotient:%s",q);
  25. caltrans(n);
  26. printf("\ntransmitted frame:%s",m);
  27. printf("\nEnter transmitted freme:");
  28. scanf("\n%s",m);
  29. printf("CRC checking\n");
  30. crc(n);
  31. printf("\n\nlast remainder:%s",r);
  32. for(i=0;i<16;i++)
  33. if(r[i]!='0')
  34. flag=1;
  35. else
  36. continue;
  37. if(flag==1)
  38. printf("Error during transmission");
  39. else
  40. printf("\n\nReceived freme is correct");
  41. }
  42. void crc(int n)
  43. {
  44. int i,j;
  45. for(i=0;i<n;i++)
  46. temp[i]=m[i];
  47. for(i=0;i<16;i++)
  48. r[i]=m[i];
  49. printf("\nintermediate remainder\n");
  50. for(i=0;i<n-16;i++)
  51. {
  52. if(r[0]=='1')
  53. {
  54. q[i]='1';
  55. calram();
  56. }
  57. else
  58. {
  59. q[i]='0';
  60. shiftl();
  61. }
  62. r[16]=m[17+i];
  63. r[17]='\0';
  64. printf("\nremainder %d:%s",i+1,r);
  65. for(j=0;j<=17;j++)
  66. temp[j]=r[j];
  67. }
  68. q[n-16]='\0';
  69. }
  70. void calram()
  71. {
  72. int i,j;
  73. for(i=1;i<=16;i++)
  74. r[i-1]=((int)temp[i]-48)^((int)g[i]-48)+48;
  75. }
  76. void shiftl()
  77. {
  78. int i;
  79. for(i=1;i<=16;i++)
  80. r[i-1]=r[i];
  81. }
  82. void caltrans(int n)
  83. {
  84. int i,k=0;
  85. for(i=n-16;i<n;i++)
  86. m[i]=((int)m[i]-48)^((int)r[k++]-48)+48;
  87. m[i]='\0';
  88. }

OUTPUT:-

[root@localhost nwcn]# vi 1.c
[root@localhost nwcn]# cc 1.c
[root@localhost nwcn]# ./a.out
Enter the binary data
1011
The msg before adding checksum:
10110000000000000000
The checksum calculated:
1011000101101011
The code word is:10111011000101101011
Enter the transmitted code word
10111011000101101011
Received msg:10111011000101101011
The checksum is:0000000000000000
No error in the msg
[root@localhost nwcn]# cc 1.c
[root@localhost nwcn]# ./a.out
Enter the binary data
1101
The msg before adding checksum:
11010000000000000000
The checksum calculated:
1101000110101101
The code word is:11011101000110101101
Enter the transmitted code word
10111101000110101101
Received msg:10111101000110101101
The checksum is:0110000011000110
Error in the msg


Learn More :