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 using namespace std; 28 29 class Ccrc16 { 30 private: 31 unsigned int crcval; 32 char ss[5]; 33 public: Ccrc16()34 Ccrc16() { crcval = 0xFFFF; } ~Ccrc16()35 ~Ccrc16() {}; reset()36 void reset() { crcval = 0xFFFF;} val()37 unsigned int val() {return crcval;} sval()38 string sval() { 39 const char *smft = "%04X"; 40 snprintf(ss,sizeof(ss), smft, crcval); 41 return ss; 42 } update(char c)43 void update(char c) { 44 crcval ^= c; 45 for (int i = 0; i < 8; ++i) { 46 if (crcval & 1) 47 crcval = (crcval >> 1) ^ 0xA001; 48 else 49 crcval = (crcval >> 1); 50 } 51 } crc16(char c)52 unsigned int crc16(char c) { 53 update(c); 54 return crcval; 55 } crc16(string s)56 unsigned int crc16(string s) { 57 reset(); 58 for (size_t i = 0; i < s.length(); i++) 59 update((char)(s[i] & 0xFF)); // only use lower half of unicode 60 return crcval; 61 } scrc16(string s)62 string scrc16(string s) { 63 crc16(s); 64 return sval(); 65 } 66 }; 67 68 #endif 69