]>
git.zerfleddert.de Git - proxmark3-svn/blob - 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
5 //-----------------------------------------------------------------------------
7 //-----------------------------------------------------------------------------
10 #define CRC16_POLY_CCITT 0x1021
11 #define CRC16_POLY 0x8408
12 #define CRC16_POLY_LEGIC 0xB400
14 unsigned short update_crc16( unsigned short crc
, unsigned char c
)
16 unsigned short i
, v
, tcrc
= 0;
19 for (i
= 0; i
< 8; i
++) {
20 tcrc
= ( (tcrc
^ v
) & 1 ) ? ( tcrc
>> 1 ) ^ CRC16_POLY
: tcrc
>> 1;
24 return ((crc
>> 8) ^ tcrc
) & 0xffff;
27 uint16_t crc16(uint8_t const *message
, int length
, uint16_t remainder
, uint16_t polynomial
) {
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
;
38 remainder
= (remainder
<< 1);
45 uint16_t crc16_ccitt(uint8_t const *message
, int length
) {
46 return crc16(message
, length
, 0xffff, CRC16_POLY_CCITT
);
49 uint16_t crc16_ccitt_kermit(uint8_t const *message
, int length
) {
50 return bit_reverse_uint16(crc16(message
, length
, 0x0000, CRC16_POLY_CCITT
));
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
);
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;
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);