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" |
6b6815bc |
10 | #define CRC16_POLY_CCITT 0x1021 |
11 | #define CRC16_POLY 0x8408 |
1d546439 |
12 | #define CRC16_POLY_LEGIC 0xB400 |
47cbb2d4 |
13 | |
fdcc61d3 |
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++) { |
6b6815bc |
20 | tcrc = ( (tcrc ^ v) & 1 ) ? ( tcrc >> 1 ) ^ CRC16_POLY : tcrc >> 1; |
fdcc61d3 |
21 | v >>= 1; |
22 | } |
23 | |
6b6815bc |
24 | return ((crc >> 8) ^ tcrc) & 0xffff; |
fdcc61d3 |
25 | } |
47cbb2d4 |
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) { |
6b6815bc |
46 | return crc16(message, length, 0xffff, CRC16_POLY_CCITT); |
47cbb2d4 |
47 | } |
ad6219fc |
48 | |
a71ece51 |
49 | uint16_t crc16_ccitt_kermit(uint8_t const *message, int length) { |
6b6815bc |
50 | return bit_reverse_uint16(crc16(message, length, 0x0000, CRC16_POLY_CCITT)); |
a71ece51 |
51 | } |
1d546439 |
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 | |
a71ece51 |
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 | } |