Detect and correct errors using Hamming(7,4) codes. Take 4 data bits, generate 3 parity bits, introduce a single-bit flip error, and write logic to identify the exact error position and correct it.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'm outlining Python functions to encode 4 data bits into 7-bit Hamming code with parity bits at positions 1, 2, and 4, then detect and correct single-bit errors using syndrome calculation. Next, I'll implement this encode-decode-error flow.
A ((7,4)) Hamming code takes 4 data bits and inserts 3 parity bits at positions that are powers of two. With positions numbered from 1 to 7, the layout is:
Parity bit (p1) covers all positions whose index has the least significant bit set (1, 3, 5, 7), (p2) covers positions with the second bit set (2, 3, 6, 7), and (p4) covers positions with the third bit set (4, 5, 6, 7). You choose the parity bits so that each covered group has even parity.
Here is a complete Python example that encodes 4 data bits, introduces a single‑bit error, computes the syndrome to locate the bad bit, and corrects it:
python
import random
def encode_hamming(d1, d2, d3, d4):
# compute parity bits for even parity
p1 = d1 ^ d2 ^ d4 # covers positions 1,3,5,7
p2 = d1 ^ d3 ^ d4 # covers positions 2,3,6,7
p4 = d2 ^ d3 ^ d4 # covers positions 4,5,6,7
# build codeword [pos1..pos7]
code = [p1, p2, d1, p4, d2, d3, d4]
return code
def introduce_error(code):
err_pos = random.randint(0, 6) # 0-based index into code list
code_err = code.copy()
code_err[err_pos] ^= 1 # flip the bit
return code_err, err_pos + 1 # return 1-based position
def syndrome(code):
# recompute parity checks over received code
s1 = code[0] ^ code[2] ^ code[4] ^ code[6] # positions 1,3,5,7
s2 = code[1] ^ code[2] ^ code[5] ^ code[6] # positions 2,3,6,7
s4 = code[3] ^ code[4] ^ code[5] ^ code[6] # positions 4,5,6,7
# combine syndrome bits into an error position
return s1 + (s2 << 1) + (s4 << 2) # 0 means no error
def correct(code):
syn = syndrome(code)
if syn != 0:
# flip the bit at position syn (1-based); convert to 0-based index
idx = syn - 1
code[idx] ^= 1
return code, syn
# Example usage:
data = [1, 0, 1, 1] # d1,d2,d3,d4
codeword = encode_hamming(*data)
print("Original codeword (pos1..pos7):", codeword)
received, flipped = introduce_error(codeword)
print("Received with error at position", flipped, ":", received)
corrected, syn = correct(received)
print("Syndrome =", syn, "(0 means no error)")
print("Corrected codeword:", corrected)
A sample run might print:
code
Original codeword (pos1..pos7): [1, 1, 1, 0, 0, 1, 1]
Received with error at position 5 : [1, 1, 1, 0, 1, 1, 1]
Syndrome = 5 (0 means no error)
Corrected codeword: [1, 1, 1, 0, 0, 1, 1]
The syndrome value 5 tells you exactly which 1‑based bit position was flipped; flipping that bit yields the original codeword.