Reputation: 45
I'm a novice programmer and also new to Python. I'm having to use an old version, 2.5.2, for a project I've been assigned at work. I've got this code shown below that takes a hex input file and extracts part of the hex file and writes it to an output file. The problem is that now it is supposed to be converted to a binary file. I've been looking at several different ways to do this and have not found anything that works. I would like to use the code I have, as much as possible, to save me from having to do a rewrite and debug. As a beginner, that is a big concern, but maybe there is no way around this? I was hopeing I could just simply take my finished hex file and convert it to a bin file. That does not seem very eligant, given my existing code, but it also proving to be elusive trying to apply what I've found searchnig under "changing a hex file to a bin file". Hopefully I'm overlooking something trivial. Any ideas or suggestions would be appreciated. Thanks.
import sys, os
m = open('myfile','w')
fileName = sys.argv[1]
inFile = open(fileName,'r')
objFile = inFile.readlines()
end = len(objFile)
filter_01 = 0
filter_02 = 0
filter_key = 0
ran = []
for idx, line in enumerate(objFile):
if line[:7] == '/origin':
filter_01 = idx + 1
if line[:8] == '03 00 01':
filter_02 = idx
if filter_01 == filter_02:
filter_key = filter_01 + 1
ran = range(filter_key, end)
m.write(objFile[filter_key -1][0:47])
m.write("\n")
m.write(objFile[filter_key -1][:47])
m.write("\n")
for idx in ran:
m.write(objFile[idx]),
m.close()
Upvotes: 2
Views: 2420
Reputation: 56654
I've rewritten this a bit more cleanly; depending on the exact format of the hex file, you may need to modify it a bit, but it should be a good starting point.
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)
Upvotes: 0
Reputation: 208475
From looking at your code it looks like your hex file has groups of two hex digits separated by whitespace, so the first step here is to figure out how to convert a hex string like '1d e3'
into binary. Since we are writing this to a file I will show how to convert this to a Python string, where each character represents a byte (I will also show for Python 3.x, where there is a separate bytes type):
Python 2.x:
>>> ''.join(x.decode('hex') for x in '1d e3'.split())
'\x1d\xe3'
Python 3.x:
>>> bytes(int(x, 16) for x in '1d e3'.split())
b'\x1d\xe3'
Once you have a binary string like this you can write it to a file, just make sure you use the binary mode, for example:
m = open('myfile', 'wb')
Upvotes: 2
Reputation: 3194
Second line - add "b" to opening mode, so it looks like:
... = open(<path>, "wb")
"b" means "binary".
Also, use "with" (I dont remember if that was in 2.5.2, but if not, import it from future). It is safer, you'll be sure that no matter what, file will be opened and closed properly.
Upvotes: 1