Search code examples
pythonnetworkingcrccrc16

CRC implementation in python


Here is my code for the implementation of a CRC in python:

import math

divisors  = [0b1100000001111, 0b11000000000000101, 0b10001000000100001, 0b1011, 0b10011,0b00000111, 0b11001]

def get_Length(arg):
    return math.floor(math.log2(arg)) +1

def CRC(message, type):
    print("Message ",bin(message)[2:], hex(message))
    # int message_length = get_Length(message);
    divisor_length = get_Length(divisors[type])
    divisor = divisors[type]
    print("Divisor: ",bin(divisor)[2:], hex(divisor))
    message = message << (divisor_length-1)

    old_message = message
    while( (message >> (divisor_length-1)) !=0 ):
        ml = get_Length(message)

        divisor_copy = divisor << (ml-divisor_length)

        message = message ^ divisor_copy

    print(bin(message)[2:], hex(message))
    print(bin(old_message| message)[2:], hex(old_message|message), end="\n\n")

def main():
   CRC(0b1101011011, 4)
   CRC(0x34ec, 1)
main()

The first message is from this Wikipedia example and gives the correct result. However the second one (x34ec), which demonstrates a CRC-16 is not giving the correct result (correct result). I'm attaching the output snapshot as well:

enter image description here.

It would be appreciative if somebody can shed some light on it.

Thanks in advance.


Solution

  • There are many CRC-16's. I count 30 here alone, and I'm sure there are more in use that are not in that catalog.

    The one you have implemented is the CRC-16/UMTS in that catalog, also known as CRC-16/BUYPASS and CRC-16/VERIFONE. It is the most straightforward of definitions, with the bits in and bits out not reflected, with an initial value of zero, and with no final exclusive-or.

    The result CRC you implemented on the message 34 ec can in fact be found directly in your linked "correct result", on the fourth row of the table which is labeled "CRC-16/BUYPASS".

    If you want to implement a different CRC-16, the first thing you need to do is specify which one. That specification is the polynomial, reflection of input and output, initial value, and final exclusive-or value.