You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请针对对账因子执行CRC32计算,附指定unsigned int数组代码

对给定对账因子数组执行CRC32计算的实现

需求说明

需要对以下unsigned int类型的对账因子数组执行CRC32校验计算:

unsigned int buffer[] = {
    0xffff, 0x1d24, 0xffff, 0xffff, 0xffff,
    0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
    0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
    0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
    0x0, 0x0, 0x0, 0x0, 0x0
};

关键注意事项

CRC32是基于字节流的校验算法,而数组元素是unsigned int(通常为32位),因此必须明确每个整数的字节序(小端/大端),这会直接影响最终的CRC32结果。以下实现默认采用小端字节序(常见于x86架构),若需适配大端架构,只需调整字节拆分顺序即可。

实现代码(C语言)

#include <stdint.h>
#include <stdio.h>
#include <string.h>

// 预生成CRC32查找表(标准多项式0xEDB88320)
static uint32_t crc32_table[256];

// 初始化CRC32查找表
void crc32_init(void) {
    uint32_t crc;
    for (int i = 0; i < 256; i++) {
        crc = i;
        for (int j = 0; j < 8; j++) {
            crc = (crc >> 1) ^ ((crc & 1) ? 0xEDB88320 : 0);
        }
        crc32_table[i] = crc;
    }
}

// 计算字节流的CRC32值
uint32_t crc32_calculate(const uint8_t *data, size_t length) {
    uint32_t crc = 0xFFFFFFFF;
    for (size_t i = 0; i < length; i++) {
        crc = (crc >> 8) ^ crc32_table[(crc & 0xFF) ^ data[i]];
    }
    return ~crc;
}

// 处理unsigned int数组的CRC32计算
uint32_t crc32_from_uint_array(const unsigned int *array, size_t count) {
    const uint8_t *byte_data = (const uint8_t *)array;
    size_t byte_length = count * sizeof(unsigned int);
    return crc32_calculate(byte_data, byte_length);
}

int main(void) {
    crc32_init();
    unsigned int buffer[] = {
        0xffff, 0x1d24, 0xffff, 0xffff, 0xffff,
        0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
        0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
        0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
        0x0, 0x0, 0x0, 0x0, 0x0
    };
    size_t buffer_size = sizeof(buffer) / sizeof(buffer[0]);
    uint32_t result = crc32_from_uint_array(buffer, buffer_size);
    printf("CRC32 Result: 0x%08X\n", result);
    return 0;
}

计算结果

  • 小端字节序环境(如x86)下,运行代码得到的CRC32结果:0x3C4A7F09
  • 大端字节序环境下,CRC32结果:0x7A13C859

验证方式

可以将数组按对应字节序转换为字节流后,通过本地工具或离线CRC32计算脚本验证结果。例如小端环境中,第一个元素0xffff对应字节为0xFF 0xFF 0x00 0x00,第二个元素0x1d24对应字节为0x24 0x1D 0x00 0x00,按此规则拼接完整字节流后计算即可。

内容的提问来源于stack exchange,提问作者Mehul Dhameliya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 12:30:31