Skip to content

Instantly share code, notes, and snippets.

@mreid
Created October 29, 2013 00:17
Show Gist options
  • Save mreid/7207139 to your computer and use it in GitHub Desktop.
Save mreid/7207139 to your computer and use it in GitHub Desktop.
Python implementation of Hamming (7,4) encoding.
# 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)
@SaloniGandhi
Copy link

can you please explain the parity function

@apraetor
Copy link

apraetor commented Apr 6, 2016

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.

@FluxIX
Copy link

FluxIX commented Apr 28, 2016

Why not implement (8, 4) hamming code?

@maliwari
Copy link

maliwari commented Mar 3, 2017

Hi!
when trying to process it, it gives wrong answer..
I've checked it myself manually

@bicycleprincess
Copy link

It's wrong.

@JacekPiotrowski235849
Copy link

is it ok?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment