本文共 1808 字,大约阅读时间需要 6 分钟。
最近在项目中需要使用crc32计算校验和,首先尝试使用Python3的zlib库,通过zlib.crc32()函数计算得到校验和为1089448862作为参考值。接着尝试使用网上找到的C代码,结果发现计算结果与Python3的结果不符。于是决定从zlib源码入手,深入探索crc32的实现原理。
在Python3中,使用zlib.crc32()函数计算校验和非常简单,直接调用函数即可得到结果。例如:
import zlibbytesData = b"\x01\x02\x03\x04\x05\x06\x07\x08\x09"retCRC = zlib.crc32(bytesData, 0)print("{}".format(retCRC)) 运行后,返回的校验和为1089448862。
接下来尝试使用zlib的C库进行计算。在Linux下,下载并编译zlib-1.2.11,使用CMake编译项目。编译完成后,发现通过自定义的main.c程序调用crc32函数,结果与Python3的结果一致。例如:
#include#include int main(void) { Bytef buf[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; uLong crcValue = crc32(0, buf, 9); printf("crc32: %d\n", crcValue); return 0;}
通过CMakeLists.txt配置,编译并运行后,输出结果与Python3一致。
为了进一步理解crc32的实现,深入分析zlib的C源码。zlib中定义了crc32_z函数,利用预先生成的crc_table数组进行计算。函数逻辑如下:
unsigned long Z_EXPORT crc32_z(crc, buf, len) { unsigned long crc; const unsigned char *buf; size_t len; if (buf == Z_NULL) return 0UL; crc = crc ^ 0xffffffffUL; while (len >= 8) { DO8; len -= 8; } if (len) do { DO1; } while (--len); return crc ^ 0xffffffffUL;} 通过理解这一函数逻辑,可以编写自定义的C代码实现相同的crc32计算功能。例如:
#include#include static const unsigned long crc_table[256] = { 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, // ...其他数据};unsigned long crc32(unsigned long crc, unsigned char *buf, size_t len) { unsigned long c; c = crc ^ 0xffffffffUL; while (len >= 8) { DO8; len -= 8; } if (len) do { DO1; } while (--len); return c ^ 0xffffffffUL;}int main(void) { unsigned char buf[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; unsigned long crcValue = crc32(0, buf, 9); printf("crc32: %d\n", crcValue); return 0;}
通过以上步骤,可以在C代码中实现与zlib一致的crc32计算,确保结果与Python3的zlib.crc32()函数一致。
转载地址:http://gdav.baihongyu.com/