# Untitled

unknown
python
2 years ago
2.2 kB
1
Indexable
Never
```1 Python Code:
2
3 # import necessary libraries
4 import random
5
6 # generate random bit stream of length n
7 def generateBits(n):
8 bits = [random.randint(0,1) for i in range(n)]
9 return bits
10
11 # generate parity bits for the given bitstream
12 def generateParityBits(bits):
13 n = len(bits)
14 # define an array to store parity bits
15 parityBits = [0] * n
16
17 # calculate position of parity bits
18 j = 0
19 i = 1
20 while (i < n):
21 if ((i & (i-1)) == 0):
22 parityBits[i-1] = sum(bits[j:i+1]) % 2
23 j = i+1
24 i = i+1
25
26 return parityBits
27
28 # generate hamming code for given bit stream
29 def hammingCode(bits):
30 # generate parity bits
31 parityBits = generateParityBits(bits)
32
33 # concatenate generated parity bits and actual bits
34 hammingCode = []
35 j = 0
36 for i in range(len(bits) + len(parityBits)):
37 if ((i+1) & i) == 0:
38 hammingCode.insert(i, parityBits[j])
39 j = j + 1
40 else:
41 hammingCode.insert(i, bits[i-j])
42
43 return hammingCode
44
45 # accepts the message if no error
46 def acceptMessage():
47 print("Message accepted")
48
49 # detect the error and correct if any
50 def detectCorrectError(hammingCode):
51 n = len(hammingCode)
52
53 # calculate parity bits
54 parityBits = generateParityBits(hammingCode)
55
56 # detect error
57 errorBit = 0
58 j = 0
59 i = 1
60 while (i < n):
61 if ((i & (i-1)) == 0):
62 errorBit = errorBit + parityBits[j] * i
63 j = j + 1
64 i = i+1
65 # correct the error
66 if (errorBit != 0):
67 hammingCode[errorBit-1] = not hammingCode[errorBit-1]
68 return hammingCode
69
70 # main code
71 if __name__ == "__main__":
72 # take input from user
73 n = int(input("Enter number of bits in bit stream: "))
74
75 # generate bit stream
76 bits = generateBits👎
77 print("Generated bits: ", bits)
78
79 # generate hamming code
80 hammingCode = hammingCode(bits)
81 print("Hamming code: ", hammingCode)
82
83 # randomly accept or reject message
84 if (random.randint(0,1) == 0):
85 print("Message rejected due to error")
86 # detect and correct error
87 correctedCode = detectCorrectError(hammingCode)
88 print("Corrected code: ", correctedCode)
89 else:
90 acceptMessage()```