one-file-projects/crc3.py

30 lines
601 B
Python
Raw Normal View History

2015-04-22 18:33:54 +02:00
from math import log, floor
tobin = lambda v: v>0 and tobin(v>>1).lstrip('0')+str(v&1) or '0'
def calcremainder(v,coeff):
n = floor(log(coeff,2))
v = v << n
r = v
while (r>>n) > 0:
m = floor(log(r,2))
p = coeff<<(m-n)
r = r ^ p
return v,r
def create(b,coeff=0b1011):
v,r = calcremainder(b,coeff)
return v+r
def check(b,coeff=0b1011):
_,r = calcremainder(b,coeff)
return r == 0
a = int("11010011101100",2)
print( "V:" + tobin( a ) )
c = create(a)+1
print("CRC-Data: " + tobin( c ) )
print("Correct?: " + ( check(c) and "Yes" or "No"))