汉明码逻辑地址(https://zhuanlan.zhihu.com/p/425393178)
实现方式一:用字符串代替二进制进行计算
1.首先根据2k ≥ n + k + 1确定需要几阶
2.在通过函数把传入的字符串转换为列表,在2的K次方位置插入0
3.最后在异或计算确认在2的K次方位置插入0或1
import math code = '0101101001' code_2 ="00001010101001" # 先根据2k ≥ n + k + 1确定需要几阶 def count_k(code:str): len_code = len(code) for k in range(len_code): if pow(2,k)-1 >= len_code + k: return k # 在通过函数把传入的字符串转换为列表,在2的K次方位置插入0 def gnerate_mk(codes:list): for code in codes: k = count_k(code) list_code = [] index = 0 count = 0 for s in range(1,k+len(code)+1): if int(math.log2(s)) == count: list_code.append('0') count += 1 else: list_code.append(code[index:index+1]) index +=1 # 最后在异或计算确认在2的K次方位置插入0或1 for s in range(k): result = 0 public_errand = pow(2, s) start = public_errand - 1 end = start + public_errand for num in range(len(list_code)): if num >= start and num <end: result += int(list_code[num]) elif num == end: start += public_errand + public_errand end += public_errand + public_errand if result % 2 == 0: list_code[public_errand - 1] = "0" else: list_code[public_errand - 1] = "1" list_str = "".join(list_code) yield list_str
print(gnerate_mk([code]).__next__()) def check_mk(code:str): k = count_k(code) check_code = "" for s in range(k): result = 0 public_errand = pow(2, s) start = public_errand - 1 end = start + public_errand for num in range(len(code)): if num >= start and num <end: result += int(code[num]) elif num == end: start += public_errand + public_errand end += public_errand + public_errand if result % 2 == 0: check_code += "0" else: check_code += "1" check_code = "".join(reversed(check_code)) check_code = int(check_code,2) if check_code == 0: return True else: raise Exception("该编码第 %s 位出现错误,反转该位置的编码即可"%check_code)
方式二:
方式二最开始我以为是错误的就想到了方式一,结果是对的。就是在2的K次方位置可以通过列表的索引直接插入。