# 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
hamming
中定义256个条目。在相关问题 更多 >
编程相关推荐