1. 程式人生 > >Python實現CRC校驗

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/[email protected]/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與的方式將高位去掉。