简单奇偶校验位方案

simple parity bit scheme

我正在尝试在 PyCharm 中创建一个简单的奇偶校验位方法,并且我编写了以下代码:

import bitarray as ba       # Library with bit strings

data = ba.bitarray(endian = 'little')       # String for data
data.frombytes('Secret message!'.encode())  # String for encoded EDC bits

def parity(bitarray):
    print("Original:\t\t\t{}".format(bitarray))
    #even = True                                        # Two protocols agree on either even or odd
    pbit = '0'                                          # Initiate parity bit as 0
    count = bitarray.count('1')                         # Count the number of ones
    print("Counted {} 1's in bitarray".format(count))
    if (count % 2) != 0:
        pbit = '1'                                      # If the bit array have an odd number of 1's we add parity bit 1 to make the number of 1's even
    print("Parity bit is {}".format(pbit))
    bitarray.append(pbit)
    print("Parity bitarray: \t{}".format(bitarray))
    return bitarray

parity(data)

我得到这个输出:

Original:        bitarray('110010101010011011000110010011101010011000101110000001001011011010100110110011101100111010000110111001101010011010000100')
Counted 58 1's in bitarray
Parity bit is 0
Parity bitarray: bitarray('1100101010100110110001100100111010100110001011100000010010110110101001101100111011001110100001101110011010100110100001001')

如你所见,1的个数是偶数,奇偶校验位是0,但我的代码在位数组的末尾添加了一个1而不是0。我已经尝试解决这个问题,但我还没找到解决办法。

问题在于将 '0' and/or '1' 分配给奇偶校验位 pbit

这些字符串似乎都被解释为二进制字符串。如果您改为使用整数值 01 作为 pbit,您的代码有效:

def parity(bitarray):
    print("Original:\t\t\t{}".format(bitarray))
    pbit = 0 # Updated line
    count = bitarray.count('1')
    print("Counted {} 1's in bitarray".format(count))
    if (count % 2) != 0:
        pbit = 1 # Updated line
    print("Parity bit is {}".format(pbit))
    bitarray.append(pbit)
    print("Parity bitarray: \t{}".format(bitarray))
    return bitarray

这可能是 bitarray 模块中的错误,因为字符串似乎在其他地方也有效,例如在 .count() 方法中,但我对 bitarray 可以肯定地说。

此外,特别是考虑到 pbit 需要是一个整数,只分配一次会更容易,直接使用表达式 pbit = count % 2,即:

def parity(bitarray):
    count = bitarray.count('1')
    pbit = count % 2
    bitarray.append(pbit)
    return bitarray