在线咨询
eetop公众号 创芯大讲堂 创芯人才网
切换到宽版

EETOP 创芯网论坛 (原名:电子顶级开发网)

手机号码,快捷登录

手机号码,快捷登录

找回密码

  登录   注册  

快捷导航
搜帖子
查看: 2217|回复: 1

[求助] hex和bin格式文件转换

[复制链接]
发表于 2017-7-13 17:13:35 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?注册

x
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)
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。要怎么修改文件名,还有这代码可以用吗,还是说各位高手有更好的方法
发表于 2018-1-18 16:00:36 | 显示全部楼层
看腳本裡就有使用方式的說明了啊
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'
您需要登录后才可以回帖 登录 | 注册

本版积分规则

关闭

站长推荐 上一条 /1 下一条

小黑屋| 关于我们| 联系我们| 在线咨询| 隐私声明| EETOP 创芯网
( 京ICP备:10050787号 京公网安备:11010502037710 )

GMT+8, 2024-3-29 14:24 , Processed in 0.015960 second(s), 6 queries , Gzip On, Redis On.

eetop公众号 创芯大讲堂 创芯人才网
快速回复 返回顶部 返回列表