Python-检查帧的CRC-16-CCITT

下面是一些检查给定消息的CRC的代码。结果为0表示未发现故障。参考:http://www.ross.net/crc/download/crc_v3.txt

选择 | 换行 | 行号
  1. def checkCRC(message):
  2.     #CRC-16-CITT poly, the CRC sheme used by ymodem protocol
  3.     poly = 0x1021
  4.     #16bit operation register, initialized to zeros
  5.     reg = 0x0000
  6.     #pad the end of the message with the size of the poly
  7.     message += '\x00\x00' 
  8.     #for each bit in the message
  9.     for byte in message:
  10.         mask = 0x80
  11.         while(mask > 0):
  12.             #left shift by one
  13.             reg<<=1
  14.             #input the next bit from the message into the right hand side of the op reg
  15.             if ord(byte) & mask:   
  16.                 reg += 1
  17.             mask>>=1
  18.             #if a one popped out the left of the reg, xor reg w/poly
  19.             if reg > 0xffff:            
  20.                 #eliminate any one that popped out the left
  21.                 reg &= 0xffff           
  22.                 #xor with the poly, this is the remainder
  23.                 reg ^= poly
  24.     return reg

标签: python

评论已关闭