]> cvs.zerfleddert.de Git - proxmark3-svn/blob - common/crc16.c
CHG: Mea culpa, misspelled Aczid 's nick.
[proxmark3-svn] / common / crc16.c
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
9 #include "crc16.h"
10 #define CRC16_POLY_CCITT 0x1021
11 #define CRC16_POLY 0x8408
12 #define CRC16_POLY_LEGIC 0xB400
13
14 unsigned short update_crc16( unsigned short crc, unsigned char c )
15 {
16 unsigned short i, v, tcrc = 0;
17
18 v = (crc ^ c) & 0xff;
19 for (i = 0; i < 8; i++) {
20 tcrc = ( (tcrc ^ v) & 1 ) ? ( tcrc >> 1 ) ^ CRC16_POLY : tcrc >> 1;
21 v >>= 1;
22 }
23
24 return ((crc >> 8) ^ tcrc) & 0xffff;
25 }
26
27 uint16_t crc16(uint8_t const *message, int length, uint16_t remainder, uint16_t polynomial) {
28
29 if (length == 0)
30 return (~remainder);
31
32 for (int byte = 0; byte < length; ++byte) {
33 remainder ^= (message[byte] << 8);
34 for (uint8_t bit = 8; bit > 0; --bit) {
35 if (remainder & 0x8000) {
36 remainder = (remainder << 1) ^ polynomial;
37 } else {
38 remainder = (remainder << 1);
39 }
40 }
41 }
42 return remainder;
43 }
44
45 uint16_t crc16_ccitt(uint8_t const *message, int length) {
46 return crc16(message, length, 0xffff, CRC16_POLY_CCITT);
47 }
48
49 uint16_t crc16_ccitt_kermit(uint8_t const *message, int length) {
50 return bit_reverse_uint16(crc16(message, length, 0x0000, CRC16_POLY_CCITT));
51 }
52
53 //ICEMAN: not working yet,
54 // This CRC-16 is used in Legic Advant systems.
55 uint16_t crc16_legic(uint8_t const *message, int length, uint16_t inital) {
56 return crc16(message, length, inital, CRC16_POLY_LEGIC);
57 }
58
59 uint16_t bit_reverse_uint16 (uint16_t value) {
60 const uint16_t mask0 = 0x5555;
61 const uint16_t mask1 = 0x3333;
62 const uint16_t mask2 = 0x0F0F;
63 const uint16_t mask3 = 0x00FF;
64
65 value = (((~mask0) & value) >> 1) | ((mask0 & value) << 1);
66 value = (((~mask1) & value) >> 2) | ((mask1 & value) << 2);
67 value = (((~mask2) & value) >> 4) | ((mask2 & value) << 4);
68 value = (((~mask3) & value) >> 8) | ((mask3 & value) << 8);
69
70 return value;
71 }
Impressum, Datenschutz