Bin文件和Hex文件相互转换

bin to hex:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:server.py

import sys
import os
import pyperclip

print()
print("*****************************************************")
print("* USAGE: python binToHex [bin_file] [hex_file_name] *")
print("*****************************************************")


if len(sys.argv) < 2:
	print("Choose bin file first!")
	exit(0)

binfile = ''
hexfile = ''

for i in range(len(sys.argv)):
	if 1 == i:
		binfile = sys.argv[i]
		print("bin path:", binfile)
	if 2 == i:
		hexfile = sys.argv[i]
		# print("hex name:", hexfile)


if not os.path.exists(binfile):
	print("Bin file was not exists!")
	exit(0)

f = open(binfile, 'rb')
line = f.read()
f.close()

hex_content = ''
for i in range(len(line)):
	if i % 16 == 0:
		hex_content = hex_content + '\n'
	hex_content = hex_content + '0x%02x,' % line[i]

pyperclip.copy(hex_content)
print("copied!")

if hexfile:
	print("hex name:", hexfile)
	if os.path.exists(hexfile):
		flag = input('"%s" exist, recover? (y/n):' % hexfile)

		if flag == 'n':
			exit(0)
		elif flag == 'y':
			print("recovered!")
		else:
			print("unknown input!")

	f = open(hexfile, 'w')
	f.write(hex_content)
	f.close()

hex to bin:

#!/usr/bin/python

import sys
import os
import struct

print()
print("*****************************************************")
print("* USAGE: python hexToBin [hex_file] [bin_file_name] *")
print("*****************************************************")


if len(sys.argv) < 2:
	print("Choose hex file first!")
	exit(0)

binfile = ''
hexfile = ''

for i in range(len(sys.argv)):
	if 1 == i:
		hexfile = sys.argv[i]
		print("hex path:", hexfile)
	if 2 == i:
		binfile = sys.argv[i]

if not os.path.exists(hexfile):
	print("Hex file was not exists!")
	exit(0)

f = open(hexfile, 'r', encoding='UTF-8')
line = f.read()
f.close()

line = line.replace('\n', '')
line = line.split(',')
line = line[:len(line)-1]

for i in range(len(line)):
	line[i] = int(line[i], 16)

if binfile:
	print("bin name:", binfile)
	if os.path.exists(binfile):
		flag = input('"%s" exist, recover? (y/n):' % binfile)

		if flag == 'n':
			exit(0)
		elif flag == 'y':
			print("recovered!")
		else:
			print("unknown input!")

	with open(binfile, 'wb')as f:
		for i in line:
			f.write(struct.pack('B', i))

	f.close()

如果对你有用的话,帮忙点赞啦!

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值