Merge pull request #140 from marshmellow42/iclass
[legacy-proxmark3.git] / common / crc.c
blob0c73474fa75888bf40878f4b41d6269e7f74510c
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 // Generic CRC calculation code.
7 //-----------------------------------------------------------------------------
8 #include "crc.h"
9 #include <stdint.h>
10 #include <stddef.h>
12 void crc_init(crc_t *crc, int order, uint32_t polynom, uint32_t initial_value, uint32_t final_xor)
14 crc->order = order;
15 crc->polynom = polynom;
16 crc->initial_value = initial_value;
17 crc->final_xor = final_xor;
18 crc->mask = (1L<<order)-1;
19 crc_clear(crc);
22 void crc_update(crc_t *crc, uint32_t data, int data_width)
24 int i;
25 for(i=0; i<data_width; i++) {
26 int oldstate = crc->state;
27 crc->state = crc->state >> 1;
28 if( (oldstate^data) & 1 ) {
29 crc->state ^= crc->polynom;
31 data >>= 1;
35 void crc_clear(crc_t *crc)
37 crc->state = crc->initial_value & crc->mask;
40 uint32_t crc_finish(crc_t *crc)
42 return ( crc->state ^ crc->final_xor ) & crc->mask;
45 //credits to iceman
46 uint32_t CRC8Maxim(uint8_t *buff, size_t size)
48 crc_t crc;
49 crc_init(&crc, 9, 0x8c, 0x00, 0x00);
50 crc_clear(&crc);
52 for (size_t i=0; i < size; ++i){
53 crc_update(&crc, buff[i], 8);
55 return crc_finish(&crc);