栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

[python] 二进制和十六进制字符相互转换

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[python] 二进制和十六进制字符相互转换

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()

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/269373.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号