数据传输中CRC校验码的实现

来源:互联网 发布:淘宝鹊桥活动怎样 编辑:程序博客网 时间:2024/05/16 17:32

CRC校验码,即循环冗余校验(Cyclic Redundancy Check),目前最为常见的一种差错校验码,CRC的信息字段和校验字的长度可以任意选定,在数据传输过程中,为了确保数据的正确性,必须使用一种数据检错方法,CRC便是最常用的一种。

CRC的原理是若在发送端发送数据,假设数据位数为K位,我们可以根据这K位的二进制码序列,以一定规则产生一个校验用的r位监督码(CRC),与原始信息一起组成一个新的二进制码,这个二进制码共有k+r位,然后将这个二进制码发送出去。至于在接收端,根据信息码和CRC码之间的规则进行检验,以确定传送中是否出错。差错理论中,称这个规则为生成多项式。



代码如下     
    
   

#include<stdio.h>     #include<stdlib.h>     #include<string.h>     #include<errno.h>     #include<unistd.h>     #include<fcntl.h>     #include<sys/stat.h>     #define BUFSIZE 1024*4            static void usage(void)    {        fprintf(stderr, "Usage: %s input_file\n", program_name);    }      static void init_crc_table(void)    {        unsigned int c;        unsigned int i,j;                for (i = 0; i < 256; i++) {            c = (unsigned )int i;            for (j = 0; j < 8; j++) {                if (c&1)                    c = 0xedb88320L^(c>>1);                else                    c = c>>1;            }            crc_table[i] = c;        }    }        static unsigned int crc32(unsigned int crc,unsigned char *buffer, unsigned int size)    {        unsigned int i;        for (i = 0; i < size; i++) {            crc = crc_table[(crc ^ buffer[i]) & 0xff] ^ (crc >> 8);        }        return crc ;    }      static int calc_img_crc(const char *in_file, unsigned int *img_crc)    {        int fd;        int nread;        int ret;        unsigned char buf[BUFSIZE];              unsigned int crc = 0xffffffff;             fd = open(in_file, O_RDONLY);        if (fd < 0) {            printf("%d:open %s.\n", __LINE__, strerror(errno));            return -1;        }                    while ((nread = read(fd, buf, BUFSIZE)) > 0) {            crc = crc32(crc, buf, nread);        }        *img_crc = crc;            close(fd);                if (nread < 0) {            printf("%d:read %s.\n", __LINE__, strerror(errno));            return -1;        }                return 0;    }        int main(int argc, char **argv)    {        int ret;        unsigned int img_crc;        const char *in_file = argv[1];            if (argc < 2) {            usage();            exit(1);        }            init_crc_table();                ret = calc_img_crc(in_file, &img_crc);        if (ret < 0) {            exit(1);        }            printf("The crc of %s is:%u\n", in_file, img_crc);            return 0;    } 
    


原创粉丝点击