Created
October 29, 2013 00:17
-
-
Save mreid/7207139 to your computer and use it in GitHub Desktop.
Python implementation of Hamming (7,4) encoding.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Hamming (7,4) Coding | |
# | |
# Reads binary stream from standard input and outputs Hamming (7,4) encoded | |
# version to standard output. | |
# | |
# USAGE: python h74-encode.py | |
# | |
# EXAMPLE: | |
# $ echo "0001" | python h74-encode.py | |
# 1000101 | |
# | |
# AUTHOR: Mark Reid <[email protected]> | |
# CREATED: 2013-10-21 | |
import sys | |
K = 4 | |
def encode(s): | |
"""Read in K=4 bits at a time and write out those plus parity bits""" | |
while len(s) >= K: | |
nybble = s[0:K] | |
sys.stdout.write(hamming(nybble)) | |
s = s[K:] | |
def hamming(bits): | |
"""Return given 4 bits plus parity bits for bits (1,2,3), (2,3,4) and (1,3,4)""" | |
t1 = parity(bits, [0,1,2]) | |
t2 = parity(bits, [1,2,3]) | |
t3 = parity(bits, [0,2,3]) | |
return bits + t1 + t2 + t3 | |
def parity(s, indicies): | |
"""Compute the parity bit for the given string s and indicies""" | |
sub = "" | |
for i in indicies: | |
sub += s[i] | |
return str(str.count(sub, "1") % 2) | |
################################################################################### | |
# Main | |
if __name__ == "__main__": | |
input_string = sys.stdin.read().strip() | |
encode(input_string) |
Why not implement (8, 4) hamming code?
Hi!
when trying to process it, it gives wrong answer..
I've checked it myself manually
It's wrong.
is it ok?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The parity function, as written, is taking the 3 bits (one from each of the indices), concatenating them into a string, and then counting the number of 1's in that resultant string. If the number of 1's mod 2 is the parity bit.
When sub = 101 then str.count() will be 2, and 2 % 2 = 0, so parity() returns 0. If sub = 111 or 010 (str.count() = 3 or 1) or anything else with an odd # of 1's then str.count() will return 1 as parity.