マッピングの使用:
# 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)
ここでのバグや非効率性は別として、 dict の 256 エントリを定義するのはあなた次第ですhamming
。