{{ message }}

Instantly share code, notes, and snippets.

# mreid/h74-encode.py

Created Oct 29, 2013
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 # 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 commented Mar 30, 2016

 can you please explain the parity function

### 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 commented Apr 28, 2016

 Why not implement (8, 4) hamming code?

### maliwari commented Mar 3, 2017

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

### bicycleprincess commented Mar 31, 2017

 It's wrong.

### JacekPiotrowski235849 commented Apr 6, 2018

 is it ok?