import bchlibBCH_POLYNOMIAL =137
BCH_BITS =5defadd_bch(wm):'''對于 str類型:a='1010' 或者 a='0b1010'bytearray(a, encoding='utf-8')= bytearray(b'0b1010')對于16進制表示的二進制 ecc''.join(format(x, '08b') for x in ecc)=str(1010)='1010''''full_wm_bytes =bytes(int(wm[i : i +8],2)for i inrange(0,len(full_wm),8))#將bin轉化為bytesa =bytearray(full_wm_bytes)print(f"{len(a)}:{a}")bch = bchlib.BCH(BCH_POLYNOMIAL, BCH_BITS)ecc = bch.encode(a)print(f"{len(ecc)}:{ecc}")ecc =''.join(format(x,'08b')for x in ecc)#使用format函數,將bytearray中存儲的十進制數轉換為二進制print(f"{len(ecc)}:{ecc}")return torch.Tensor([int(i)for i in full_wm+ecc])
構造BCH糾錯的方法
# do error correctdefdo_ec(wm):#56位BCH校驗full_wm =str(wm.numpy().tolist())[1:-1].replace('.0','').replace(',','').replace(' ','')bch = bchlib.BCH(BCH_POLYNOMIAL, BCH_BITS)full_wm =bytes(int(full_wm[i : i +8],2)for i inrange(0,len(full_wm),8))#將bin轉化為bytesfull_wm=bytearray(full_wm)wm = full_wm[:-bch.ecc_bytes]#wm = bytearray(wm, encoding='utf-8')ecc = full_wm[-bch.ecc_bytes:]#ecc = bytes(int(ecc[i : i + 8], 2) for i in range(0, len(ecc), 8))bitflips = bch.decode_inplace(wm, ecc)if bitflips !=-1:try:code = wm.decode("utf-8")print(code)except:passprint('Failed to decode')wm =''.join(format(x,'08b')for x in wm)return torch.Tensor([int(i)for i in wm])