找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 4231|回复: 1
打印 上一主题 下一主题

[代码与实例] hex和bin格式文件转换

1

主题

5

帖子

5

积分

贫民

积分
5
跳转到指定楼层
楼主
2740710202 发表于 2017-7-13 17:04:08 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
import os
import sys
from struct import *
#hex to bin
def hex_bin(hexfile,binfile):
fin = open(hexfile)
fout = open(binfile,'wb')
result =''
for hexstr in fin.readlines():
hexstr = hexstr.strip()
size = int(hexstr[1:3],16)
if int(hexstr[7:9],16) != 0:
continue
#end if
for h in range( 0, size):
b = int(hexstr[9+h*2:9+h*2+2],16)
result += pack('B',b)
#end if
fout.write(result)
result=''
#end for
fin.close()
fout.close()
# bin to hex
def bin_hex(binfile,hexfile):
fbin = open(binfile,'rb')
fhex = open(hexfile,'w')
offset = 0
seg_addr = 0
while 1:
checksum=0
result = ':'
bindata = fbin.read(0x10)
if len(bindata) == 0 :
break
#end if
result += '%02X' % len(bindata)
result += '%04X' % offset
result += '00'
checksum = len(bindata)
checksum += (offset & 0xff) + (offset >> 8)
for i in range(0,len(bindata)):
byte = unpack('B',bindata[i])
result+='%02X' % byte
checksum += byte[0]
#end for
checksum = 0x01 + ~checksum
checksum = checksum & 0xff
result += '%02X/n' % checksum
fhex.write(result)
offset += len(bindata)
if offset == 0x10000:
offset = 0
seg_addr += 1
result = ':02000004'
result += '%02X%02X' % ((seg_addr>>8) & 0xff,seg_addr & 0xff)
checksum = 0x02 + 0x04 + (seg_addr>>8) + seg_addr & 0xff
checksum = -checksum
result+='%02X' % (checksum & 0xff)
result += '/n'
fhex.write(result)
#end if
if len(bindata) < 0x10:
break
#end if
#end while
fhex.write(':00000001FF')
fbin.close()
fhex.close()
#end for
if len(sys.argv) != 4 or (sys.argv[1] != '-h' and sys.argv[1] != '-b'):
print 'usage:'
print 'convert binary format to hexadecimal format: '
print ' hexbin.py -h binfile hexfile'
print 'convert hexadecimal format to binary format:'
print ' hexbin.py -b hexfile binfile'
exit(0)
if sys.argv[1] == '-h':
bin_hex(sys.argv[2],sys.argv[3])
else:
hex_bin(sys.argv[2],sys.argv[3])

以上是网上找到的代码,但是我还是python的小白,只想先能使用,问问大家,用这个转换的话,应该一同放什么命名的文件啊,比如我的hex文件是a.hex,bin文件是b.bin。要怎么修改文件名,还有这代码可以用吗,还是说各位高手有更好的方法

回复

使用道具 举报

1

主题

5

帖子

5

积分

贫民

积分
5
沙发
2740710202  楼主| 发表于 2017-7-13 17:06:17 | 只看该作者
各位帮忙看看哟
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表