群码Python实现及应用(CRC校验)

群码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'))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值