Python实现CRC校验

来源:互联网 发布:unity3d sharesdk ios 编辑:程序博客网 时间:2024/04/30 05:56

<pre name="code" class="python"><span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">参考网址http://blog.163.com/du_minchao@126/blog/static/107495394201075114028606/</span>


上边参考网址内的计算方法亲自算一遍就知道CRC怎么使用了(就是上边的图片),搜索了一下,大部分都是C语言实现,工作期间需要用Python实现求字符串CRC校验的函数,使用查表法实现


#!/usr/bin/env python# -*- coding: utf-8 -*-POLYNOMIAL = 0x1021INITIAL_REMAINDER = 0xFFFFFINAL_XOR_VALUE = 0x0000WIDTH = 16TOPBIT = (1 << (WIDTH - 1))crcTable = {}def crcInit():SHIFT = WIDTH - 8for step in range(0, 256):remainder = step << SHIFTfor bit in range(8, 0, -1):if remainder & TOPBIT:remainder = ((remainder << 1) & 0xFFFF) ^ 0x1021else:remainder = remainder << 1crcTable[step] = remainderdef crcFast(message, nBytes):crcInit()remainder = 0xFFFFdata = 0byte = 0while byte < nBytes:data = ord(message[byte]) ^ (remainder >> (WIDTH - 8))remainder = crcTable[data] ^ ((remainder << 8)&0xFFFF)byte = byte + 1return hex(remainder)[2: ]

位移时要注意 python的整数没有最大值,而C++中不同,左移会将高位移掉,python则一直保留高位,所以通过位0xFFFF与的方式将高位去掉。


0 0
原创粉丝点击