-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhamming_code.py
More file actions
executable file
·43 lines (35 loc) · 1.6 KB
/
Copy pathhamming_code.py
File metadata and controls
executable file
·43 lines (35 loc) · 1.6 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
def calculate_parity_bits(data):
"""Generates a dynamic Hamming Code codeword."""
n = len(data)
r = 0
# 1. Figure out how many redundant (parity) bits we need
while (2 ** r) < (n + r + 1):
r += 1
# 2. Build the initial codeword array
# Put 0s in the parity positions (powers of 2) and fill the rest with data bits
codeword = []
data_index = 0
for position in range(1, n + r + 1):
# A bitwise trick: if (position & (position - 1)) == 0, it's a power of 2
if (position & (position - 1)) == 0:
codeword.append(0)
else:
codeword.append(int(data[data_index]))
data_index += 1
# 3. Calculate the actual values for the Parity Bits
for i in range(r):
parity_pos = 2 ** i
current_parity_value = 0
# Check every bit in the codeword to see if this parity bit is responsible for it
for target_pos in range(1, len(codeword) + 1):
# Bitwise AND checks if the target position is covered by the parity position
if target_pos & parity_pos:
current_parity_value ^= codeword[target_pos - 1]
# Insert the calculated parity value back into the codeword
codeword[parity_pos - 1] = current_parity_value
# Convert the list of integers back into a single string
return "".join(map(str, codeword))
if __name__ == "__main__":
data_bits = input("Enter data bits (binary): ").strip()
result = calculate_parity_bits(data_bits)
print(f"Hamming Code: {result}")