]> git.zerfleddert.de Git - proxmark3-svn/blame - common/crc16.c
small refactoring
[proxmark3-svn] / common / crc16.c
CommitLineData
bd20f8f4 1//-----------------------------------------------------------------------------
2// This code is licensed to you under the terms of the GNU GPL, version 2 or,
3// at your option, any later version. See the LICENSE.txt file for the text of
4// the license.
5//-----------------------------------------------------------------------------
6// CRC16
7//-----------------------------------------------------------------------------
8
fdcc61d3 9#include "crc16.h"
10
11unsigned short update_crc16( unsigned short crc, unsigned char c )
12{
6eaa8da9 13 unsigned short i, v, tcrc = 0;
fdcc61d3 14
6eaa8da9 15 v = (crc ^ c) & 0xff;
16 for (i = 0; i < 8; i++) {
17 tcrc = ( (tcrc ^ v) & 1 ) ? ( tcrc >> 1 ) ^ 0x8408 : tcrc >> 1;
18 v >>= 1;
19 }
fdcc61d3 20
6eaa8da9 21 return ((crc >> 8) ^ tcrc)&0xffff;
fdcc61d3 22}
23b598ee 23
24uint16_t crc16(uint8_t const *message, int length, uint16_t remainder, uint16_t polynomial) {
6eaa8da9 25
26 if (length == 0) return (~remainder);
27
28 for (int byte = 0; byte < length; ++byte) {
29 remainder ^= (message[byte] << 8);
30 for (uint8_t bit = 8; bit > 0; --bit) {
31 if (remainder & 0x8000) {
32 remainder = (remainder << 1) ^ polynomial;
33 } else {
34 remainder = (remainder << 1);
35 }
36 }
37 }
38 return remainder;
23b598ee 39}
40
41uint16_t crc16_ccitt(uint8_t const *message, int length) {
6eaa8da9 42 return crc16(message, length, 0xffff, 0x1021);
43}
44
45uint16_t crc16_ccitt_kermit(uint8_t const *message, int length) {
07b5a3c3 46 return bit_reverse_uint16(crc16(message, length, 0x0000, 0x1021));
47}
48
49uint16_t bit_reverse_uint16 (uint16_t value) {
50 const uint16_t mask0 = 0x5555;
51 const uint16_t mask1 = 0x3333;
52 const uint16_t mask2 = 0x0F0F;
53 const uint16_t mask3 = 0x00FF;
54
55 value = (((~mask0) & value) >> 1) | ((mask0 & value) << 1);
56 value = (((~mask1) & value) >> 2) | ((mask1 & value) << 2);
57 value = (((~mask2) & value) >> 4) | ((mask2 & value) << 4);
58 value = (((~mask3) & value) >> 8) | ((mask3 & value) << 8);
59
60 return value;
23b598ee 61}
Impressum, Datenschutz