Python - check CRC of a frame CRC-16-CCITT

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • highvelcty
    New Member
    • May 2010
    • 2

    #1

    Python - check CRC of a frame CRC-16-CCITT

    Here is some code to check the CRC of a given message. The result of 0 indicates no trouble found. Reference: http://www.ross.net/crc/download/crc_v3.txt
    Code:
    def checkCRC(message):
        #CRC-16-CITT poly, the CRC sheme used by ymodem protocol
        poly = 0x1021
        #16bit operation register, initialized to zeros
        reg = 0x0000
        #pad the end of the message with the size of the poly
        message += '\x00\x00' 
        #for each bit in the message
        for byte in message:
            mask = 0x80
            while(mask > 0):
                #left shift by one
                reg<<=1
                #input the next bit from the message into the right hand side of the op reg
                if ord(byte) & mask:   
                    reg += 1
                mask>>=1
                #if a one popped out the left of the reg, xor reg w/poly
                if reg > 0xffff:            
                    #eliminate any one that popped out the left
                    reg &= 0xffff           
                    #xor with the poly, this is the remainder
                    reg ^= poly
        return reg
    Last edited by bvdet; May 6 '10, 10:09 AM. Reason: Remove indent tags, add code tags
Working...