pythonfilefilesystemshamming-code

Compute Hamming Code on files


I am trying to code in Hamming code(python language) on data present in a .txt file. How can I go about it? DO I need to read out the data line by line, convert into ascii characters and then compute hamming code on it. Or is there any function or library in python that can serve as a window and can operate on the whole file as one?

Your reply is very appreciated. Than you in advance.

Edit: The scenario is a client server architecture. Client tries to upload a file to server after computing hamming code of the data and stores it in server. Later when it tries to retrieve back the file, it checks the hamming code and detects any error that may have occurred.


Solution

  • Using a mapping:

    # create a dict that maps input bytes to their hamming-encoded version.  This
    # can be pre-calculated and hard-coded, or generated at startup
    hamming = {
        0x00: 0x0000, # these numbers are nonsense.  Input byte 0x00 is
                      # being mapped to output bytes 0x0000
        0x01: 0x0101,
        ...
        0xff: 0x10cf
    }
    
    # read the source binary file
    with open('input.bin', 'r') as infile:
        data = [int(x) for x in infile.read()]
    
    # translate the input data into its encoded form (1 byte becomes 2 with parity added, etc)
    output = ''
    for byte in data:
        encoded = hamming[byte]
        output += chr((encoded >> 8) & 0xff)
        output += chr((encoded >> 0) & 0xff)
    
    # write the encoded data to a file
    with open('output.bin', 'w') as out:    
        out.write(output)
    

    Apart from any bugs and inefficiencies here, it's just up to you to define the 256 entries in the dict hamming.