crc校验

crc校验,Cyclic redundancy check,循环冗余校验,一般用来校验通信的包是否正确,收和发使用同一种校验就可以,一般是crc16位校验和crc32位校验。

 

开时钟,对test_data进行校验,校验值与标准校验值比较

1、crc16: 

static uint8_t test_data[32] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
    25, 26, 27, 28, 29, 30, 31, 32 };
static uint32_t test_data_size = 32;
static uint32_t test_crc_value = 0x305D;

uint32_t crc16_xmodem(uint8_t* data, uint32_t size)
{
    uint32_t crc_value = 0;

    crc_config_t config;
    config.init_value  = 0;
    config.poly_size   = CRC_POLY_SIZE_16;
    config.poly        = 0x1021;
    config.reverse_in  = CRC_REVERSE_IN_NONE;
    config.reverse_out = false;

    crc_init(&config);

    crc_value = crc_calc8(data, size);

    return crc_value;
}

uint32_t crc_calc8(uint8_t* data, uint32_t size)
{
    for (uint32_t i = 0; i < size; i++) {
        *((uint8_t*)CRC_DR_ADDR) = data[i];
    }

    while (CRC->CR & CRC_CR_CALC_FLAG)
        ;

    return CRC->DR;
}

2、crc32:

static uint8_t test_data[32] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
    25, 26, 27, 28, 29, 30, 31, 32 };
static uint32_t test_data_size = 32;
static uint32_t test_crc_value = 0x87E6EC25;

uint32_t crc32(uint8_t* data, uint32_t size)
{
    uint32_t crc_value = 0;

    // CRC-32
    crc_config_t config;
    config.init_value  = 0xFFFFFFFF;
    config.poly_size   = CRC_POLY_SIZE_32;
    config.poly        = 0x04C11DB7;
    config.reverse_in  = CRC_CR_REVERSE_IN_BYTE;
    config.reverse_out = true;

    crc_init(&config);

    crc_value = crc_calc8(data, size);
    crc_value ^= 0xFFFFFFFF;

    return crc_value;
}

 都使用了crc_calc8来计算crc的值,因为里面是根据size进行循环的,计算出来的校验码长度肯定是不一样的,具体的算法原理可以参考:https://blog.csdn.net/u013073067/article/details/86621770

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值