Hamming

The Hamming code can correct a single bit error.

def hamming_detect(code: list[int]):
    """Given a Hamming code return the bit position of
    the error or -1 if no error exists in the code.
    """
    bel = 0
    pb = 1
    while pb < len(code):
        ndx = pb - 1
        sum = 0
        for x in range(len(code)):
            if (x + 1) & pb == pb:
                sum += code[x]
        print('sum', sum)
        bel += (sum & 1) * pb 
        pb = pb << 1
    return bel - 1

def hamming_encode(data_bits: list[int]):
    """Given data bits as a list of integer 0 and 1s return
    the Hamming encoding as a list of 0 and 1s.
    """
    out = []

    pbp = 1
    x = 0
    y = 0
    while y < len(data_bits):
        if x == pbp - 1:
            out.append('P')
            pbp = pbp << 1
        else: 
            out.append(data_bits[y])
            y += 1
        x += 1
        
    # Now, all bits are in place.

    pbp = 1
    while pbp < len(out):
        print('pbp', pbp)
        ndx = pbp - 1
        sum = 0
        for x in range(len(out)):
            if (x + 1) & pbp == pbp:
                print('    ', x + 1, 'bit', out[x])
                sum += out[x]
        if sum & 1 == 1:
            out[ndx] = 1
        else:
            out[ndx] = 0
        pbp = pbp << 1

    return out