Python实现CRC校验

<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 = 0x1021
INITIAL_REMAINDER = 0xFFFF
FINAL_XOR_VALUE = 0x0000
WIDTH = 16
TOPBIT = (1 << (WIDTH - 1))
crcTable = {}

def crcInit():
	SHIFT = WIDTH - 8
	for step in range(0, 256):
		remainder = step << SHIFT
		for bit in range(8, 0, -1):
			if remainder & TOPBIT:
				remainder = ((remainder << 1) & 0xFFFF) ^ 0x1021
			else:
				remainder = remainder << 1
		crcTable[step] = remainder

def crcFast(message, nBytes):
	crcInit()
	remainder = 0xFFFF
	data = 0
	byte = 0
	while byte < nBytes:
		data = ord(message[byte]) ^ (remainder >> (WIDTH - 8))
		remainder = crcTable[data] ^ ((remainder << 8)&0xFFFF)
		byte = byte + 1
		
	return hex(remainder)[2: ]

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


  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值