]>
cvs.zerfleddert.de Git - proxmark3-svn/blob - common/crc.c
21019da9c0b97891d8717779e0bf7d5538924f7b
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 //-----------------------------------------------------------------------------
14 void crc_init(crc_t
*crc
, int order
, uint32_t polynom
, uint32_t initial_value
, uint32_t final_xor
)
17 crc
->polynom
= polynom
;
18 crc
->initial_value
= initial_value
;
19 crc
->final_xor
= final_xor
;
20 crc
->mask
= (1L<<order
)-1;
24 void crc_update(crc_t
*crc
, uint32_t data
, int data_width
)
26 for( int i
=0; i
< data_width
; i
++) {
27 int oldstate
= crc
->state
;
28 crc
->state
= crc
->state
>> 1;
29 if( (oldstate
^data
) & 1 ) {
30 crc
->state
^= crc
->polynom
;
36 void crc_clear(crc_t
*crc
)
38 crc
->state
= crc
->initial_value
& crc
->mask
;
41 uint32_t crc_finish(crc_t
*crc
)
43 return ( crc
->state
^ crc
->final_xor
) & crc
->mask
;
47 uint32_t CRC8Maxim(uint8_t *buff
, size_t size
)
50 crc_init(&crc
, 9, 0x8c, 0x00, 0x00);
53 for (size_t i
=0; i
< size
; ++i
)
54 crc_update(&crc
, buff
[i
], 8);
56 return crc_finish(&crc
);
59 uint32_t CRC8Legic(uint8_t *buff
, size_t size
) {
61 // Poly 0x63, reversed poly 0xC6, Init 0x55, Final 0x00
63 crc_init(&crc
, 8, 0xC6, 0x55, 0);
66 for ( int i
= 0; i
< size
; ++i
)
67 crc_update(&crc
, buff
[i
], 8);
68 return SwapBits(crc_finish(&crc
), 8);
71 uint32_t SwapBits(uint32_t value
, int nrbits
) {
72 uint32_t newvalue
= 0;
73 for(int i
= 0; i
< nrbits
; i
++) {
74 newvalue
^= ((value
>> i
) & 1) << (nrbits
- 1 - i
);