1 /*
2 * Copyright (C) 2015-2017 Alibaba Group Holding Limited
3 */
4
5 #include "CheckSumUtils.h"
6
7
UpdateCRC8(uint8_t crcIn,uint8_t byte)8 uint8_t UpdateCRC8(uint8_t crcIn, uint8_t byte)
9 {
10 uint8_t crc = crcIn;
11 uint8_t i;
12
13 crc ^= byte;
14
15 for (i = 0; i < 8; i++) {
16 if (crc & 0x01) {
17 crc = (crc >> 1) ^ 0x8C;
18 } else {
19 crc >>= 1;
20 }
21 }
22 return crc;
23 }
24
25
CRC8_Init(CRC8_Context * inContext)26 void CRC8_Init( CRC8_Context *inContext )
27 {
28 inContext->crc = 0;
29 }
30
31
CRC8_Update(CRC8_Context * inContext,const void * inSrc,size_t inLen)32 void CRC8_Update( CRC8_Context *inContext, const void *inSrc, size_t inLen )
33 {
34 const uint8_t *src = (const uint8_t *) inSrc;
35 const uint8_t *srcEnd = src + inLen;
36 while ( src < srcEnd ) {
37 inContext->crc = UpdateCRC8(inContext->crc, *src++);
38 }
39 }
40
41
CRC8_Final(CRC8_Context * inContext,uint8_t * outResult)42 void CRC8_Final( CRC8_Context *inContext, uint8_t *outResult )
43 {
44 //inContext->crc = UpdateCRC8(inContext->crc, 0);
45 *outResult = inContext->crc & 0xffu;
46 }
47
48
49 /*******************************************************************************/
50
UpdateCRC16(uint16_t crcIn,uint8_t byte)51 uint16_t UpdateCRC16(uint16_t crcIn, uint8_t byte)
52 {
53 uint32_t crc = crcIn;
54 uint32_t in = byte | 0x100;
55
56 do {
57 crc <<= 1;
58 in <<= 1;
59 if (in & 0x100) {
60 ++crc;
61 }
62 if (crc & 0x10000) {
63 crc ^= 0x1021;
64 }
65 } while (!(in & 0x10000));
66 return crc & 0xffffu;
67 }
68
CRC16_Init(CRC16_Context * inContext)69 void CRC16_Init( CRC16_Context *inContext )
70 {
71 inContext->crc = 0;
72 }
73
74
CRC16_Update(CRC16_Context * inContext,const void * inSrc,size_t inLen)75 void CRC16_Update( CRC16_Context *inContext, const void *inSrc, size_t inLen )
76 {
77 const uint8_t *src = (const uint8_t *) inSrc;
78 const uint8_t *srcEnd = src + inLen;
79 while ( src < srcEnd ) {
80 inContext->crc = UpdateCRC16(inContext->crc, *src++);
81 }
82 }
83
84
CRC16_Final(CRC16_Context * inContext,uint16_t * outResult)85 void CRC16_Final( CRC16_Context *inContext, uint16_t *outResult )
86 {
87 inContext->crc = UpdateCRC16(inContext->crc, 0);
88 inContext->crc = UpdateCRC16(inContext->crc, 0);
89 *outResult = inContext->crc & 0xffffu;
90 }
91
92