要求将十六进制文件转换为 bin 文件 EN
最编程
2024-05-04 22:47:17
...
import os
import sys
import optparse
VERBOSE = False
def read_hexfile(fname):
if VERBOSE: print('Reading from {0}'.format(fname))
data = False
res = []
with open(fname, 'r') as inf:
for line in inf:
if data:
if line[:8] == '03 00 01':
data = False
else:
res.extend(int(hex, 16) for hex in line.split())
else:
if line[:7] == '/origin':
data = True
else:
# skip non-data
pass
if VERBOSE: print(' {0} bytes read'.format(len(res)))
return res
def write_binfile(fname, data):
if VERBOSE: print('Writing to {0}'.format(fname))
with open(fname, 'wb') as outf:
outf.write(''.join(chr(i) for i in data))
if VERBOSE: print(' {0} bytes written'.format(len(data)))
def main(input, output):
data = read_hexfile(input)
write_binfile(output, data)
if __name__=="__main__":
parser = optparse.OptionParser()
parser.add_option('-i', '--input', dest='input', help='name of HEX input file')
parser.add_option('-o', '--output', dest='output', help='name of BIN output file')
parser.add_option('-v', '--verbose', dest='verbose', help='output extra status information', action='store_true', default=False)
(options, args) = parser.parse_args()
VERBOSE = options.verbose
main(options.input, options.output)
上一篇: 初始数据类型