-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcrc16.cpp
95 lines (77 loc) · 1.62 KB
/
crc16.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* Code to calculate CRC16-CCITT
* was adopted from the following site
* http://srecord.sourceforge.net/crc16-ccitt.html
*
*/
#include "crc16.h"
#define poly 0x1021 /* crc-ccitt mask */
uint16_t CRC16::get_crc16(char *text)
{
uint8_t ch, i;
good_crc = 0xffff;
i = 0;
while((ch=text[i])!=0)
{
update_good_crc(ch);
i++;
}
augment_message_for_good_crc();
return good_crc;
}
void CRC16::update_good_crc(uint8_t ch)
{
uint8_t i, v, xor_flag;
/*
Align test bit with leftmost bit of the message byte.
*/
v = 0x80;
for (i=0; i<8; i++)
{
if (good_crc & 0x8000)
{
xor_flag= 1;
}
else
{
xor_flag= 0;
}
good_crc = good_crc << 1;
if (ch & v)
{
/*
Append next bit of message to end of CRC if it is not zero.
The zero bit placed there by the shift above need not be
changed if the next bit of the message is zero.
*/
good_crc= good_crc + 1;
}
if (xor_flag)
{
good_crc = good_crc ^ poly;
}
/*
Align test bit with next bit of the message byte.
*/
v = v >> 1;
}
}
void CRC16::augment_message_for_good_crc()
{
uint8_t i, xor_flag;
for (i=0; i<16; i++)
{
if (good_crc & 0x8000)
{
xor_flag= 1;
}
else
{
xor_flag= 0;
}
good_crc = good_crc << 1;
if (xor_flag)
{
good_crc = good_crc ^ poly;
}
}
}