Debian Codegraph @

src/include/crc16.h

raw
1 // ----------------------------------------------------------------------------
2 // Copyright (C) 2014
3 // David Freese, W1HKJ
4 //
5 // This file is part of flmsg
6 //
7 // flrig is free software; you can redistribute it and/or modify
8 // it under the terms of the GNU General Public License as published by
9 // the Free Software Foundation; either version 3 of the License, or
10 // (at your option) any later version.
11 //
12 // flrig is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 // GNU General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program. If not, see <http://www.gnu.org/licenses/>.
19 // ----------------------------------------------------------------------------
20
21 #ifndef _CCRC16_
22 #define _CCRC16_
23
24 #include <string>
25 #include "debug.h"
26
27 class Ccrc16 {
28 private:
29 unsigned int crcval;
30 char ss[5];
31 public:
32 Ccrc16() { crcval = 0xFFFF; }
33 ~Ccrc16() {};
34 void reset() { crcval = 0xFFFF;}
35 unsigned int val() {return crcval;}
36 std::string sval() {
37 const char *smft = "%04X";
38 snprintf(ss,sizeof(ss), smft, crcval);
39 return ss;
40 }
41 void update(char c) {
42 crcval ^= c;
43 for (int i = 0; i < 8; ++i) {
44 if (crcval & 1)
45 crcval = (crcval >> 1) ^ 0xA001;
46 else
47 crcval = (crcval >> 1);
48 }
49 }
50 unsigned int crc16(char c) {
51 update(c);
52 return crcval;
53 }
54 unsigned int crc16(std::string s) {
55 reset();
56 for (size_t i = 0; i < s.length(); i++)
57 update((char)(s[i] & 0xFF)); // only use lower half of unicode
58 return crcval;
59 }
60 std::string scrc16(std::string s) {
61 crc16(s);
62 return sval();
63 }
64 };
65
66 #endif