简单的校验和算法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wm5920/article/details/80761899

c版本

#include <stdio.h>
#include <stdlib.h>
#include "crc16.h"

static mu16 check(mu8* addr, mu32 count) ;

int main(int argc, char** argv) {

    char aData[] = {0x7E, 0x7F, 0x06, 0x01};

    //mu16 nResult = Toolbox_crc16(aData, 4);

    mu16 nResult = check(aData, 4);

    printf("==[%x]==\n", nResult);

    return (EXIT_SUCCESS);
}

static mu16 check(mu8* addr, mu32 count) {
    register long sum = 0;

    mbool flag = MFALSE;
    mu16 checksum = 0;

    while (count > 1) {
        /* This is the inner loop */
        sum += *(unsigned short*) addr++;
        count -= 2;
    }

    /*  Add left-over byte, if any  */
    if (count > 0) {
        sum += *(unsigned char *) addr;
        flag = MTRUE;
    }

    /*  Fold 32-bit sum to 16 bits  */
    while (sum >> 16){
        sum = (sum & 0xffff) + (sum >> 16);
    }

    checksum = ~sum;

    if (flag){
        checksum = ((checksum & 0x00ff) << 8) | ((checksum & 0xff00) >> 8);
    }

    return checksum;
}

java版

public static short check(byte[] addr, int count) {
        /*  Compute Checksum for "count" bytes beginning at location "addr".    */
        long sum = 0;

        boolean flag = false;
        short checksum = 0;

        int i = 0;       
        short s;
        while (count > 1) {

            s = (short)(addr[i]  +  addr[i+1] << 8 );
            /* This is the inner loop */
            sum +=  s;
            count -= 2;
            i++;
        }

        /*  Add left-over byte, if any  */
        if (count > 0) {
            sum +=  addr[i];
            flag = true;
        }

        /*  Fold 32-bit sum to 16 bits  */
        while ((sum >> 16) > 0) {
            sum = (sum & 0xffff) + (sum >> 16);
        }

        checksum = (short)~sum;

        if (flag) {
            checksum = (short)(((checksum & 0x00ff) << 8) | ((checksum & 0xff00) >> 8));
        }

        return checksum;

    }

猜你喜欢

转载自blog.csdn.net/wm5920/article/details/80761899