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()
如果对你有用的话,帮忙点赞啦!