我正在尝试用 Python 编写汉明码编码,但我被困在必须计算奇偶校验位索引的部分。
汉明码是使用额外的奇偶校验位来识别单个错误。创建代码字如下:
将所有为 2 的幂的位位置标记为奇偶校验位。(位置 1、2、4、8、16、32、64 等)所有其他位位置用于要编码的数据。(位置 3、5、6、7、9、10、11、12、13、14、15、17 等)每个奇偶校验位计算代码字中某些位的奇偶校验。奇偶校验位的位置决定了它交替检查和跳过的位序列。
位置 1:检查 1 位、跳过 1 位、检查 1 位、跳过 1 位等(1、3、5、7、9、11、13、15、...)
位置2:校验2位、跳过2位、校验2位、跳过2位等(2,3,6,7,10,11,14,15,...)
位置4:校验4位、跳过4位、校验4位、跳过4位等(4,5,6,7,12,13,14,15,20,21,22,23,...)
位置8:校验8位、跳过8位、校验8位、跳过8位等(8-15,24-31,40-47,...)
16位:校验16位、跳过16位、校验16位、跳过16位等(16-31,48-63,80-95,...)
位置 32:检查 32 位、跳过 32 位、检查 32 位、跳过 32 位等(32-63,96-127,160-191,...)等。
如果它检查的位置中的总个数是奇数,则将奇偶校验位设置为 1。如果它检查的位置中的总个数是偶数,则将奇偶校验位设置为 0。
本质上,我需要在索引处生成奇偶校验位:
P1 = [1,3,5,7,9,11 等]
P2 = [2,3,6,7,10,11 等]
P3 = [4,5,6,7,12,13 等]
P4 = [8,9,10,11,12,13,14,15,24 等]
找到这些后,我需要将这些位相加,以 2 为模,然后插入正确的位置。
我的代码查找插入位置
# Function to calculate Hamming code
def hamming(number):
print("Hamming Code - Beginning to encode. ")
listP = half_ham(number)
print("Inserting P at relevant indices: ", listP)
encode = []
print("Length of messgae: ",len(listP), "bits.")
index = []
for i, j in enumerate(listP, start = 1):
print("i", i)
if isPowerOfTwo(i):
index = gen_indices(i, len(listP))
c = [ listP[i] for i in index]
print("C: ", c)
# Function to insert P at positions which are powers of 2
def half_ham(bin_str):
parity_positions = [2**i for i in range(0, len(bin_str))]
ret = []
current_index = 1
indexDict = {}
while (len(bin_str) > 0):
if current_index in parity_positions:
ret.append('P')
else:
ret.append(bin_str[0])
bin_str = bin_str[1:]
current_index += 1
return ret
输入:
hamming("10101010")
电流输出:
Hamming Code - Beginning to encode.
Inserting P at relevant indices: ['P', 'P', '1', 'P', '0', '1', '0', 'P', '1', '0', '1', '0']
Length of message: 12
现在我需要找到正确的奇偶校验索引(如上的 P1、P2、P3)。
最初,我试图用 while 循环生成索引。这一直有效,直到我得到一个列表超出范围错误。另外,它几乎不可读。
# Function to get a list of the indexes
def gen_indices(x, y):
jump = x
current = x
index = []
while current <= y:
index.extend(list(range(current, current+jump)))
print("before current:",current)
current += jump * 2
return index
现在我正在尝试使用 enumerate 函数来获取所需索引的列表。就像是:
def index(x, listP):
for x, y in enumerate(listP, start = x):
print(x,y)
期望的输出是:
P1= 1 P P2= 2 P 3 1 3 1 5 0 6 1 7 1 7 1
然后,我可以将这些位添加到一个字符串中。任何人都可以帮忙吗?
我希望这是有道理的。我对编码很陌生,所以请不要判断。