数据校验--累加和校验

1、SC(SumCheck)累加和校验
    所谓累加和校验实现方式有很多种,最常用的一种是在一次通讯数据包的最后加入一个字节的校验数据。这个字节内容为前面数据包中全部数据的忽略进位的按字节累加和。比如下面的例子:
    我们要传输的信息为: 6、23、4
    加上校验和后的数据包:6、23、4、33
    这里 33 为前三个字节的校验和。接收方收到全部数据后对前三个数据进行同样的累加计算,如果累加和与最后一个字节相同的话就认为传输的数据没有错误。
2、软件实现;
    #include<stdio.h>

    static unsigned char Fun_SC_Create(unsigned char *p1, unsigned short int len);
    static unsigned char Fun_SC_Check(unsigned char *p1, unsigned short int len);
    unsigned char Data_11B[11] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10};

    /**
     *********************************************************************************
     * @file             main.c
     * @auther           li
     * @version          1.1.1
     * @data             2018-12-26 19:02:01
     * @brief            主函数
     * @param
     * @retval           none
     * @attention
     *********************************************************************************
    */
    int
    main(int argc, char **argv)
    {
        printf("This is a SC Data Check test!!!\r\n");

        Data_11B[10] = Fun_SC_Create(Data_11B, 10);

        if(Fun_SC_Check(Data_11B, 10) == Data_11B[10])
        {
            printf("Check is ok!!!\r\n");
        }
        else
        {
            printf("Check is err!!!\r\n");
        }

        while(1);
    }

    /**
     *********************************************************************************
     * @file             main.c
     * @auther           li
     * @version          1.1.1
     * @data             2018-12-26 19:02:27
     * @brief            函数功能: 生成SC
     * @param            p1:待生成校验数据的首地址
     *                  len:待生成校验数据长度
     * @retval           校验后的数据
     * @attention
     *********************************************************************************
    */
    static unsigned char
    Fun_SC_Create (unsigned char *p1, unsigned short int len)
    {
        unsigned char sum = 0;
        for(;len > 0; len--)
        {
            sum += *p1++;
        }

        return sum;
    }

    /**
     *********************************************************************************
     * @file             main.c
     * @auther           li
     * @version          1.1.1
     * @data             2018-12-26 19:02:33
     * @brief            函数功能: SC 校验
     * @param            p1:待校验的数据首地址
     *                  len:待校验数据长度
     * @retval           校验后的数据
     * @attention
     *********************************************************************************
    */
    static unsigned char
    Fun_SC_Check(unsigned char *p1, unsigned short int len)
    {
        unsigned char sum=0;

        for(;len > 0; len--)
        {
            sum += p1[len-1];
        }

        return sum;
    }


    /** 实验结果
     **************************
     * This is a SC Data Check test!!!
     * Check is ok!!!
     ***************************
     */
 

猜你喜欢

转载自blog.csdn.net/tyustli/article/details/85267241