博客
关于我
CRC32计算方法
阅读量:239 次
发布时间:2019-03-01

本文共 1765 字,大约阅读时间需要 5 分钟。

最近在项目中需要使用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/

你可能感兴趣的文章
Redis 配置文件杂项。
查看>>
Python web自动化测试 —— 文件上传
查看>>
Python web自动化测试 —— 文件上传!
查看>>
Python Web自动化测试开发环境搭建(附安装包与虚拟机环境)
查看>>
python win32api键盘_Python win32api.keybd_event模拟键盘输入
查看>>
python Windows显示当前鼠标坐标
查看>>
python Workbook 表格宽度
查看>>
python | ggplot,一个超强的 Python 库!
查看>>
python | unoconv,一个超厉害的 Python 库!
查看>>
python | webassets,一个超强的 Python 库!
查看>>
python | werkzeug,一个不可思议的 Python 库!
查看>>
python | xlsxwriter,一个实用的 Python 库!
查看>>
python | xlwings,一个非常实用的 Excel 相关的 Python 库!
查看>>
python读取含中文的json
查看>>
python | 提升代码迭代速度的Python重载方法
查看>>
python | 深入理解Python并发编程中的GIL限制与解决方案
查看>>
Python | 爬虫实战——亚马逊搜索页监控(附详细源码)
查看>>
python | 高效使用Python工具自动生成模块文档的秘诀
查看>>
python 一个list去除另一个list中的值
查看>>
python 三大框架的 介绍。
查看>>