]>
cvs.zerfleddert.de Git - proxmark3-svn/blob - common/crc.c
b6d7551e1da4493c34a00dc1d2cb5442dc1d9736
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 //-----------------------------------------------------------------------------
6 // Generic CRC calculation code.
7 //-----------------------------------------------------------------------------
12 #define BITMASK(X) (1 << (X))
14 uint32_t reflect(uint32_t v
, int b
) {
16 for (int i
= 0; i
< b
; ++i
) {
18 v
|= BITMASK((b
- 1) - i
);
20 v
&= ~BITMASK((b
- 1) - i
);
26 void crc_init(crc_t
*crc
, int order
, uint32_t polynom
, uint32_t initial_value
, uint32_t final_xor
)
29 crc
->polynom
= polynom
;
30 crc
->initial_value
= initial_value
;
31 crc
->final_xor
= final_xor
;
32 crc
->mask
= (1L<<order
)-1;
36 void crc_update(crc_t
*crc
, uint32_t data
, int data_width
)
39 for(i
=0; i
<data_width
; i
++) {
40 int oldstate
= crc
->state
;
41 crc
->state
= crc
->state
>> 1;
42 if( (oldstate
^data
) & 1 ) {
43 crc
->state
^= crc
->polynom
;
49 void crc_clear(crc_t
*crc
)
51 crc
->state
= crc
->initial_value
& crc
->mask
;
54 uint32_t crc_finish(crc_t
*crc
)
56 return ( crc
->state
^ crc
->final_xor
) & crc
->mask
;
60 uint32_t CRC8Maxim(uint8_t *buff
, size_t size
)
63 crc_init(&crc
, 9, 0x8c, 0x00, 0x00);
66 for (size_t i
=0; i
< size
; ++i
){
67 crc_update(&crc
, buff
[i
], 8);
69 return crc_finish(&crc
);
72 // width=8 poly=0x1d, init=0xc7 (0xe3 - WRONG! but it mentioned in MAD datasheet) refin=false refout=false xorout=0x00 name="CRC-8/MIFARE-MAD"
73 uint32_t CRC8Mad(uint8_t *buff
, size_t size
) {
75 crc_init(&crc
, 8, reflect(0x1d, 8), reflect(0xc7, 8), 0);
76 for (int i
= 0; i
< size
; ++i
)
77 crc_update(&crc
, reflect(buff
[i
], 8), 8);
79 return reflect(crc_finish(&crc
), 8);