2014-09-12 05:23:46 +08:00
|
|
|
#include "crc32.h"
|
|
|
|
|
|
|
|
#define htole32(x) (x)
|
|
|
|
#define CRC32_PRESET 0xFFFFFFFF
|
|
|
|
|
2019-03-10 07:00:59 +08:00
|
|
|
static void crc32_byte(uint32_t *crc, const uint8_t value);
|
2014-09-12 05:23:46 +08:00
|
|
|
|
2019-03-10 18:20:22 +08:00
|
|
|
static void crc32_byte(uint32_t *crc, const uint8_t value) {
|
2014-09-12 05:23:46 +08:00
|
|
|
/* x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x + 1 */
|
|
|
|
const uint32_t poly = 0xEDB88320;
|
|
|
|
|
|
|
|
*crc ^= value;
|
|
|
|
for (int current_bit = 7; current_bit >= 0; current_bit--) {
|
|
|
|
int bit_out = (*crc) & 0x00000001;
|
|
|
|
*crc >>= 1;
|
|
|
|
if (bit_out)
|
|
|
|
*crc ^= poly;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-10 18:20:22 +08:00
|
|
|
void crc32_ex(const uint8_t *data, const size_t len, uint8_t *crc) {
|
2014-09-12 05:23:46 +08:00
|
|
|
uint32_t desfire_crc = CRC32_PRESET;
|
|
|
|
for (size_t i = 0; i < len; i++) {
|
2019-03-10 07:00:59 +08:00
|
|
|
crc32_byte(&desfire_crc, data[i]);
|
2014-09-12 05:23:46 +08:00
|
|
|
}
|
2020-05-03 21:15:02 +08:00
|
|
|
uint32_t crctmp = htole32(desfire_crc);
|
2020-05-06 19:38:51 +08:00
|
|
|
for (size_t i = 0; i < sizeof(uint32_t); i++) {
|
2020-05-03 21:15:02 +08:00
|
|
|
crc[i] = ((uint8_t *) &crctmp)[i];
|
|
|
|
}
|
2014-09-12 05:23:46 +08:00
|
|
|
}
|
|
|
|
|
2019-03-10 18:20:22 +08:00
|
|
|
void crc32_append(uint8_t *data, const size_t len) {
|
2019-03-10 07:00:59 +08:00
|
|
|
crc32_ex(data, len, data + len);
|
2019-03-12 07:12:26 +08:00
|
|
|
}
|