joo gustavo a amorim gabriel kunz email joaogustavoamorimgmail com and gabrielkunzuergs edu br coding date apr 2019 black true this code implement the hamming code https en wikipedia orgwikihammingcode in telecommunication hamming codes are a family of linear errorcorrecting codes hamming codes can detect up to twobit errors or correct onebit errors without detection of uncorrected errors by contrast the simple parity code cannot correct errors and can detect only an odd number of bits in error hamming codes are perfect codes that is they achieve the highest possible rate for codes with their block length and minimum distance of three the implemented code consists of a function responsible for encoding the message emitterconverter return the encoded message a function responsible for decoding the message receptorconverter return the decoded message and a ack of data integrity how to use to be used you must declare how many parity bits sizepari you want to include in the message it is desired for test purposes to select a bit to be set as an error this serves to check whether the code is working correctly lastly the variable of the messageword that must be desired to be encoded text how this work declaration of variables sizepari be text converts the messageword text to binary using the texttobits function encodes the message using the rules of hamming encoding decodes the message using the rules of hamming encoding print the original message the encoded message and the decoded message forces an error in the coded text variable decodes the message that was forced the error print the original message the encoded message the bit changed message and the decoded message imports functions of binary conversion texttobitsmsg 011011010111001101100111 textfrombits 011011010111001101100111 msg functions of hamming code param sizepar how many parity bits the message must have param data information bits return message to be transmitted by unreliable medium bits of information merged with parity bits emitterconverter4 101010111111 1 1 1 1 0 1 0 0 1 0 1 1 1 1 1 1 emitterconverter5 101010111111 traceback most recent call last valueerror size of parity don t match with size of data sorted information data for the size of the output data data position template parity parity bit counter counter position of data bits performs a template of bit positions who should be given and who should be parity sorts the data to the new output size calculates parity bit counter one for a given parity counter to control the loop reading mount the message receptorconverter4 1111010010111111 1 0 1 0 1 0 1 1 1 1 1 1 true data position template parity parity bit counter counter p data bit reading list of parity received performs a template of bit positions who should be given and who should be parity sorts the data to the new output size calculates the parity with the data sorted information data for the size of the output data data position feedback parity parity bit counter counter p data bit reading performs a template position of bits who should be given and who should be parity sorts the data to the new output size calculates parity bit counter one for a certain parity counter to control loop reading mount the message example how to use number of parity bits sizepari 4 location of the bit that will be forced an error be 2 messageword to be encoded and decoded with hamming text inputenter the word to be read text message01 convert the message to binary binarytext texttobitstext prints the binary of the string printtext input in binary is binarytext total transmitted bits totalbits lenbinarytext sizepari printsize of data is strtotalbits printn message exchange printdata to send binarytext dataout emitterconvertersizepari binarytext printdata converted joindataout datareceiv ack receptorconvertersizepari dataout print data receive joindatareceiv tt data integrity strack printn force error printdata to send binarytext dataout emitterconvertersizepari binarytext printdata converted joindataout forces error dataoutbe 1 dataoutbe 0 0 dataoutbe 1 printdata after transmission joindataout datareceiv ack receptorconvertersizepari dataout print data receive joindatareceiv tt data integrity strack joão gustavo a amorim gabriel kunz email joaogustavoamorim gmail com and gabriel kunz uergs edu br coding date apr 2019 black true this code implement the hamming code https en wikipedia org wiki hamming_code in telecommunication hamming codes are a family of linear error correcting codes hamming codes can detect up to two bit errors or correct one bit errors without detection of uncorrected errors by contrast the simple parity code cannot correct errors and can detect only an odd number of bits in error hamming codes are perfect codes that is they achieve the highest possible rate for codes with their block length and minimum distance of three the implemented code consists of a function responsible for encoding the message emitterconverter return the encoded message a function responsible for decoding the message receptorconverter return the decoded message and a ack of data integrity how to use to be used you must declare how many parity bits sizepari you want to include in the message it is desired for test purposes to select a bit to be set as an error this serves to check whether the code is working correctly lastly the variable of the message word that must be desired to be encoded text how this work declaration of variables sizepari be text converts the message word text to binary using the text_to_bits function encodes the message using the rules of hamming encoding decodes the message using the rules of hamming encoding print the original message the encoded message and the decoded message forces an error in the coded text variable decodes the message that was forced the error print the original message the encoded message the bit changed message and the decoded message imports functions of binary conversion text_to_bits msg 011011010111001101100111 text_from_bits 011011010111001101100111 msg functions of hamming code param size_par how many parity bits the message must have param data information bits return message to be transmitted by unreliable medium bits of information merged with parity bits emitter_converter 4 101010111111 1 1 1 1 0 1 0 0 1 0 1 1 1 1 1 1 emitter_converter 5 101010111111 traceback most recent call last valueerror size of parity don t match with size of data sorted information data for the size of the output data data position template parity parity bit counter counter position of data bits performs a template of bit positions who should be given and who should be parity sorts the data to the new output size calculates parity parity bit counter bit counter one for a given parity counter to control the loop reading mount the message parity bit counter receptor_converter 4 1111010010111111 1 0 1 0 1 0 1 1 1 1 1 1 true data position template parity parity bit counter counter p data bit reading list of parity received performs a template of bit positions who should be given and who should be parity sorts the data to the new output size calculates the parity with the data sorted information data for the size of the output data data position feedback parity parity bit counter counter p data bit reading performs a template position of bits who should be given and who should be parity sorts the data to the new output size calculates parity parity bit counter bit counter one for a certain parity counter to control loop reading mount the message parity bit counter example how to use number of parity bits sizepari 4 location of the bit that will be forced an error be 2 message word to be encoded and decoded with hamming text input enter the word to be read text message01 convert the message to binary binarytext text_to_bits text prints the binary of the string print text input in binary is binarytext total transmitted bits totalbits len binarytext sizepari print size of data is str totalbits print n message exchange print data to send binarytext dataout emitterconverter sizepari binarytext print data converted join dataout datareceiv ack receptorconverter sizepari dataout print data receive join datareceiv t t data integrity str ack print n force error print data to send binarytext dataout emitterconverter sizepari binarytext print data converted join dataout forces error dataout be 1 dataout be 0 0 dataout be 1 print data after transmission join dataout datareceiv ack receptorconverter sizepari dataout print data receive join datareceiv t t data integrity str ack
import numpy as np



def text_to_bits(text, encoding="utf-8", errors="surrogatepass"):
    
    bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:]
    return bits.zfill(8 * ((len(bits) + 7) // 8))


def text_from_bits(bits, encoding="utf-8", errors="surrogatepass"):
    
    n = int(bits, 2)
    return n.to_bytes((n.bit_length() + 7) // 8, "big").decode(encoding, errors) or "\0"



def emitter_converter(size_par, data):
    
    if size_par + len(data) <= 2**size_par - (len(data) - 1):
        raise ValueError("size of parity don't match with size of data")

    data_out = []
    parity = []
    bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data) + 1)]

    
    data_ord = []
    
    data_out_gab = []
    
    qtd_bp = 0
    
    cont_data = 0

    for x in range(1, size_par + len(data) + 1):
        
        
        if qtd_bp < size_par:
            if (np.log(x) / np.log(2)).is_integer():
                data_out_gab.append("P")
                qtd_bp = qtd_bp + 1
            else:
                data_out_gab.append("D")
        else:
            data_out_gab.append("D")

        
        if data_out_gab[-1] == "D":
            data_ord.append(data[cont_data])
            cont_data += 1
        else:
            data_ord.append(None)

    
    qtd_bp = 0  
    for bp in range(1, size_par + 1):
        
        cont_bo = 0
        
        cont_loop = 0
        for x in data_ord:
            if x is not None:
                try:
                    aux = (bin_pos[cont_loop])[-1 * (bp)]
                except IndexError:
                    aux = "0"
                if aux == "1" and x == "1":
                    cont_bo += 1
            cont_loop += 1
        parity.append(cont_bo % 2)

        qtd_bp += 1

    
    cont_bp = 0  
    for x in range(size_par + len(data)):
        if data_ord[x] is None:
            data_out.append(str(parity[cont_bp]))
            cont_bp += 1
        else:
            data_out.append(data_ord[x])

    return data_out


def receptor_converter(size_par, data):
    
    
    data_out_gab = []
    
    qtd_bp = 0
    
    cont_data = 0
    
    parity_received = []
    data_output = []

    for x in range(1, len(data) + 1):
        
        
        if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer():
            data_out_gab.append("P")
            qtd_bp = qtd_bp + 1
        else:
            data_out_gab.append("D")

        
        if data_out_gab[-1] == "D":
            data_output.append(data[cont_data])
        else:
            parity_received.append(data[cont_data])
        cont_data += 1

    
    data_out = []
    parity = []
    bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data_output) + 1)]

    
    data_ord = []
    
    data_out_gab = []
    
    qtd_bp = 0
    
    cont_data = 0

    for x in range(1, size_par + len(data_output) + 1):
        
        
        if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer():
            data_out_gab.append("P")
            qtd_bp = qtd_bp + 1
        else:
            data_out_gab.append("D")

        
        if data_out_gab[-1] == "D":
            data_ord.append(data_output[cont_data])
            cont_data += 1
        else:
            data_ord.append(None)

    
    qtd_bp = 0  
    for bp in range(1, size_par + 1):
        
        cont_bo = 0
        
        cont_loop = 0
        for x in data_ord:
            if x is not None:
                try:
                    aux = (bin_pos[cont_loop])[-1 * (bp)]
                except IndexError:
                    aux = "0"
                if aux == "1" and x == "1":
                    cont_bo += 1
            cont_loop += 1
        parity.append(str(cont_bo % 2))

        qtd_bp += 1

    
    cont_bp = 0  
    for x in range(size_par + len(data_output)):
        if data_ord[x] is None:
            data_out.append(str(parity[cont_bp]))
            cont_bp += 1
        else:
            data_out.append(data_ord[x])

    ack = parity_received == parity
    return data_output, ack