crc16.c (1234B)
1 #include "crc16.h" 2 #include <stdlib.h> 3 4 uint16_t crc16_calculate(const uint8_t *data, uint16_t size) { 5 #define POLY16 (uint16_t)0x8005 6 uint16_t out = 0; 7 int bits_read = 0, bit_flag; 8 /* Sanity check: */ 9 if (data == NULL) 10 return 0; 11 while (size > 0) { 12 bit_flag = out >> 15; 13 /* Get next bit: */ 14 out <<= 1; 15 out |= (*data >> (7 - bits_read)) & 1; 16 /* Increment bit counter: */ 17 bits_read++; 18 if (bits_read > 7) { 19 bits_read = 0; 20 data++; 21 size--; 22 } 23 /* Cycle check: */ 24 if (bit_flag) { 25 out ^= POLY16; 26 } 27 } 28 return out; 29 } 30 31 uint32_t crc32_calculate(const uint8_t *data, uint16_t size) { 32 #define POLY32 (uint32_t)0xEDB88320 33 uint32_t out = 0; 34 int bits_read = 0, bit_flag; 35 /* Sanity check: */ 36 if (data == NULL) 37 return 0; 38 while (size > 0) { 39 bit_flag = out >> 31; 40 /* Get next bit: */ 41 out <<= 1; 42 out |= (*data >> (7 - bits_read)) & 1; 43 /* Increment bit counter: */ 44 bits_read++; 45 if (bits_read > 7) { 46 bits_read = 0; 47 data++; 48 size--; 49 } 50 /* Cycle check: */ 51 if (bit_flag) { 52 out ^= POLY32; 53 } 54 } 55 return out; 56 } 57