1 //
2 // crc_example.c
3 //
4 // Cyclic redundancy check (CRC) example. This example demonstrates
5 // how a CRC can be used to validate data received through un-reliable
6 // means (e.g. a noisy channel). A CRC is, in essence, a strong
7 // algebraic error detection code that computes a key on a block of data
8 // using base-2 polynomials.
9 // SEE ALSO: checksum_example.c
10 // fec_example.c
11 //
12
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <getopt.h>
16
17 #include "liquid.h"
18
19 // print usage/help message
usage()20 void usage()
21 {
22 printf("crc_example [options]\n");
23 printf(" u/h : print usage\n");
24 printf(" n : input data size (number of uncoded bytes)\n");
25 printf(" v : checking scheme, (crc32 default):\n");
26 liquid_print_crc_schemes();
27 }
28
29
main(int argc,char * argv[])30 int main(int argc, char*argv[])
31 {
32 // options
33 unsigned int n = 32; // data length (bytes)
34 crc_scheme check = LIQUID_CRC_32; // error-detection scheme
35
36 int dopt;
37 while((dopt = getopt(argc,argv,"uhn:v:")) != EOF){
38 switch (dopt) {
39 case 'h':
40 case 'u': usage(); return 0;
41 case 'n': n = atoi(optarg); break;
42 case 'v':
43 check = liquid_getopt_str2crc(optarg);
44 if (check == LIQUID_CRC_UNKNOWN) {
45 fprintf(stderr,"error: unknown/unsupported error-detection scheme \"%s\"\n\n",optarg);
46 exit(1);
47 }
48 break;
49 default:
50 exit(1);
51 }
52 }
53
54 // validate input
55
56 unsigned int i;
57
58 // initialize data array, leaving space for key at the end
59 unsigned char data[n+4];
60 for (i=0; i<n; i++)
61 data[i] = rand() & 0xff;
62
63 // append key to data message
64 crc_append_key(check, data, n);
65
66 // check uncorrupted data
67 printf("testing uncorrupted data... %s\n", crc_check_key(check, data, n) ? "pass" : "FAIL");
68
69 // corrupt message and check data again
70 data[0]++;
71 printf("testing corrupted data... %s\n", crc_check_key(check, data, n) ? "pass" : "FAIL (ok)");
72
73 printf("done.\n");
74 return 0;
75 }
76