5, checksum (Checksum) to achieve

An 8-bit checksum implemented

1.8 checksum calculation step of sending end:

  (1) the checksum field set to zero.

  (2) the need to verify the data in 8-bit units as the numbers sequentially summed, and the resulting binary code is negated, plus 1, to give the final checksum.

  (3) the result obtained is stored in the checksum field.

2. The receiving end checksum of the steps of:

  (1) The content to be verified (including the checksum fields) in units of 8 bits as a digital, binary one sequentially summing, if the result is 0 indicates correct, otherwise an error.

3. implementation code:

 1 static unsigned char sg_ucSeq = 0;
 2 typedef struct
 3 {
 4     unsigned long hid;
 5     unsigned long cid;
 6 
 7     unsigned char type;
 8     unsigned char len;    
 9     unsigned char checksum;
10     unsigned char seq;
11 
12     unsigned char userData[MAX_USER_DATA_SIZE];
13 }DATA_T;
14 
15 #define MAX_USER_DATA_SIZE       40
16 #define DATA_HEADER_LEN (sizeof(DATA_T) - MAX_USER_DATA_SIZE)
17 
18 // 发送端调用
19 unsigned char MakeCheckSum8(DATA_T *pData)
20 {
21     unsigned char ucCheckSum = 0;
22     unsigned char ucNum;
23     unsigned char *pucDat = (unsigned char *)pData;
24 
25     for(ucNum=0;ucNum<pData->len;ucNum++){
26         ucCheckSum += pucDat[ucNum];
27     }
28 
29     ucCheckSum = ~ucCheckSum;
30     ucCheckSum++;
31     
32     return ucCheckSum;
33 }
34 
35 // 接收端调用
36 unsigned char CheckData8(DATA_T *pData)
37 {
38     unsigned char ucCheckSum = 0;
39     unsigned char ucNum;
40     unsigned char *pucDat = (unsigned char *)pData;
41 
42     for(ucNum=0;ucNum<pData->len;ucNum++){
43         ucCheckSum += pucDat[ucNum];
44     }
45     
46     return ucCheckSum;
47 }
48 void create_common_msg(DATA_T *pfdata, unsigned char type, unsigned char *pdata, int len)
49 {
50     memset(pdata, 0, sizeof(DATA_T));
51 
52     pfdata->clientid = 0x12345678;
53     pfdata->type = type;
54     pfdata->len = FJ_DATA_HEADER_LEN + len;
55     pfdata->checksum = 0;
56     pfdata->seq = sg_ucSeq++;
57 
58     if (len > 0)
59     {
60         memcpy(pfdata->userData, pdata, len);
61     }
62 
63     pfdata->checksum     = MakeCheckSum8(pdata);
64 
65     return;
66 }

Guess you like

Origin www.cnblogs.com/sbtblogs/p/12228406.html