群码Python实现及应用(CRC校验)
class Bn:
def __init__(self, bits='0'):
self._bits = bits
def __getitem__(self, key):
return Bn(self._bits[key])
def __len__(self):
return len(self._bits)
def __str__(self):
return self._bits
def __xor__(self, other):
return Bn(bin(int(self._bits, 2) ^ int(other._bits, 2))[2:])
def __add__(self, other):
return self ^ other
def __iadd__(self, other):
return self ^ other
def __sub__(self, other):
return self ^ other
def __mul__(self, other):
product = Bn()
for i, ch in enumerate(reversed(other._bits)):
if ch == '1':
product += Bn(self._bits+'0'*i)
return product
def __truediv__(self, other):
return divmod(self, other)[0]
def __mod__(self, other):
return divmod(self, other)[1]
def __divmod__(self, other):
ldividend = len(self)
ld = len(other)
if ldividend < ld:
return Bn(), self
i = ld
dividend = self[:ld]
quotient = ''
while True:
r = dividend ^ other
deltal = ld-len(r)
quotient += '1'
if i+deltal > ldividend:
break
quotient += '0'*(deltal-1)
dividend = Bn(r._bits+self._bits[i:i+deltal])
i += deltal
return Bn(quotient), r
def CRC(frame, generator):
return Bn(frame+'0'*(len(generator)-1)) % Bn(generator)
print(Bn('10100001000') + Bn('1001'))
print(Bn('10100001000') - Bn('1001'))
print(Bn('10100001000') * Bn('1001'))
print(Bn('10100001000') / Bn('1001'))
print(Bn('10100001000') % Bn('1001'))
print('--------------')
print(CRC('10100001', '1001'))
print(CRC('11010110', '1001'))