• API
• FAQ
• Tools
• Trends
• Archive
SHARE
TWEET

# hammingcode

phillip1882 May 22nd, 2012 203 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. def encode(message):
2.    parity = 1
3.    while len(message)+parity+1 > 2**parity:
4.       parity += 1
5.    for i in range(0,parity):
6.       message = message[:2**i-1]+"_"+message[2**i-1:]
7.    check = 0
8.    while check < parity:
9.       dist = 2**check
10.       pos = dist-1
11.       total = 0
12.       while pos < len(message):
13.          for i in range(pos,pos+dist):
14.             try:
15.                if message[i] != "_":
16.                  total += int(message[i])
17.             except IndexError:
18.                break
19.          pos += 2*dist
20.       if total &1 == 1:
21.          message = message[:dist-1] +"1" +message[dist:]
22.       else:
23.          message = message[:dist-1] +"0" +message[dist:]
24.       check += 1
25.    return message
26.
27. def decode(message):
28.    parity = 1
29.    while len(message)+parity+1 > 2**parity:
30.       parity += 1
31.    check = 0
32.    wrong = 0
33.    while check < parity:
34.       dist = 2**check
35.       pos = dist-1
36.       total = 0
37.       while pos <= len(message):
38.          for i in range(pos,pos+dist):
39.             try:
40.                if message[i] != "_":
41.                   total += int(message[i])
42.             except IndexError:
43.                break
44.          pos += 2*dist
45.       if total &1 != 0:
46.          wrong += dist
47.       check += 1
48.    if wrong != 0:
49.       if message[wrong-1] == "0":
50.          message = message[:wrong-1] +"1" +message[wrong:]
51.       else:
52.          message = message[:wrong-1] +"0" +message[wrong:]
53.       print("error found, corrected")
54.    return message
55. print(encode("100101"))
56. print(decode("0111001101"))
RAW Paste Data
Top