forked from kennyledet/Algorithm-Implementations
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHammingCode.py
More file actions
69 lines (57 loc) · 1.48 KB
/
HammingCode.py
File metadata and controls
69 lines (57 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""
AUTHOR : Alex Mathew
EMAIL : alexmathew003@gmail.com
"""
"""For a given binary word, print out its corresponding Hamming Coded word"""
import math
def FindKeyBits(n):
keyBits=[]
pad = int(math.ceil(math.log(n)/math.log(2)))
for i in xrange(1, n+1):
b = "{0:b}".format(i)
b=b.zfill(pad)
keyBits.append(b)
return keyBits
def IsPowerOf2(x):
return ((x&(x-1))==0)
def XOR(a, b):
return str(int(a)^int(b))
def FindParityCount(m):
r = math.ceil((math.log(m)/math.log(2))+1)
return int(r)
def CalculateParity(keyBits, data, parityTrack):
parity = '0'
pbCount = 0
for elem in keyBits:
if not IsPowerOf2(int(elem,2)):
if elem[-parityTrack]=='1':
parity = XOR(parity, data[pbCount-int(elem,2)])
else:
pbCount+=1
return parity
def ComputeHamming(data):
dataLen = len(data)
parityCount = FindParityCount(dataLen)
hammingLen = dataLen + parityCount
keyBits = FindKeyBits(hammingLen)
hammingCode = []
dataTrack = -1
parityTrack = 1
for i in xrange(1, hammingLen+1):
if IsPowerOf2(i):
parity = CalculateParity(keyBits, data, parityTrack)
hammingCode.append(parity)
parityTrack+=1
else:
hammingCode.append(data[dataTrack])
dataTrack-=1
hammingCode.reverse()
for i in hammingCode:
print i,
def main():
print '\n'
data = raw_input("Enter the word to be encoded : ")
print '\nThe Hamming encoded word for', data, 'is : ',
ComputeHamming(data)
if __name__ == '__main__':
main()