简体   繁体   English

将十六进制文件转换为bin文件

[英]Converting a hex file to a bin file

I'm a novice programmer and also new to Python. 我是一个新手程序员,也是Python的新手。 I'm having to use an old version, 2.5.2, for a project I've been assigned at work. 对于我在工作中分配的项目,我必须使用旧版本2.5.2。 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. 我希望我可以简单地将已完成的十六进制文件转换为bin文件。 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". 考虑到我现有的代码,这似乎不太合适,但事实证明,尝试应用在“将十六进制文件更改为bin文件”下找到的searchnig的内容还难以捉摸。 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()

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. 通过查看您的代码,您的十六进制文件看起来好像有由空格分隔的两个十六进制数字组成的组,因此此处的第一步是弄清楚如何将十六进制字符串(如'1d e3'转换为二进制。 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字符串,其中每个字符代表一个字节(我还将针对Python 3.x进行演示,其中存在单独的字节类型):

  • Python 2.x: Python 2.x:

     >>> ''.join(x.decode('hex') for x in '1d e3'.split()) '\\x1d\\xe3' 
  • Python 3.x: 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')

Second line - add "b" to opening mode, so it looks like: 第二行-在打开模式中添加“ b”,如下所示:

... = open(<path>, "wb")

"b" means "binary". “ b”表示“二进制”。

Also, use "with" (I dont remember if that was in 2.5.2, but if not, import it from future ). 另外,请使用“ with”(我不记得它是否在2.5.2中,但如果不存在,请从future导入)。 It is safer, you'll be sure that no matter what, file will be opened and closed properly. 这样做比较安全,您可以确保无论如何,文件都可以正确打开和关闭。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM