Python实现CRC校验

发布时间:2019-09-15 10:08:40编辑:auto阅读(4494)

    <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与的方式将高位去掉。


关键字