博客
关于我
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/

你可能感兴趣的文章
NetworkX系列教程(11)-graph和其他数据格式转换
查看>>
Networkx读取军械调查-ITN综合传输网络?/读取GML文件
查看>>
Net与Flex入门
查看>>
net包之IPConn
查看>>
NFinal学习笔记 02—NFinalBuild
查看>>
NFS共享文件系统搭建
查看>>
nfs复习
查看>>
NFS网络文件系统
查看>>
ng 指令的自定义、使用
查看>>
nginx + etcd 动态负载均衡实践(二)—— 组件安装
查看>>
nginx + etcd 动态负载均衡实践(四)—— 基于confd实现
查看>>
Nginx + Spring Boot 实现负载均衡
查看>>
Nginx + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
Nginx Location配置总结
查看>>
Nginx upstream性能优化
查看>>
Nginx 中解决跨域问题
查看>>
Nginx 动静分离与负载均衡的实现
查看>>
Nginx 反向代理 MinIO 及 ruoyi-vue-pro 配置 MinIO 详解
查看>>
Nginx 反向代理解决跨域问题
查看>>