I am trying to make a simple paritybit method in PyCharm, and I've written this code:
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)
And I get this output:
Original: bitarray('110010101010011011000110010011101010011000101110000001001011011010100110110011101100111010000110111001101010011010000100')
Counted 58 1's in bitarray
Parity bit is 0
Parity bitarray: bitarray('1100101010100110110001100100111010100110001011100000010010110110101001101100111011001110100001101110011010100110100001001')
As you can see, the number of 1's is even, and the parity bit is 0, but my code has added a 1 at the end of the bitarray istead of a 0. I have tried to fix the problem, but I haven't managed to find a solution.
The issue is with the assignment of '0'
and/or '1'
to the parity bit pbit
.
It seems that these strings, are both interpreted as binary ones. If you instead use the integer values 0
and 1
for pbit
your code works:
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
This may be a bug in the bitarray
module as it seems that strings seem to work in other places, such as in the .count()
method, but I don't know enough about bitarray
to say for certain.
Also, especially given that the pbit
needs to be an integer, it would be easier to just assign it once, using the expression pbit = count % 2
directly, i.e.:
def parity(bitarray):
count = bitarray.count('1')
pbit = count % 2
bitarray.append(pbit)
return bitarray