Python-十六进制与字符串转换脚本
Posted 小狐狸FM
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python-十六进制与字符串转换脚本相关的知识,希望对你有一定的参考价值。
前言
hex表示十六进制,str表示字符串
在输入十六进制数的时候可以以0x
开头
在转换成十六进制的时候删除了0x
的标识符,每两位是一个十六进制数
一、示例
[1]. Hex转str
[2]. Hex转Str(文件读取)
[3]. Str转Hex
[4]. Str转Hex(文件读取)
二、代码
# coding=utf-8
# 作者:小狐狸FM
# 功能:十六进制数与字符串转换
def GetList(string):
'''输入字符串,两两组合返回列表'''
result = []
now = ""
time = 1
for i in string:
now += i
if time%2==0:
result.append(now)
now = ""
time += 1
return result
# print(GetList("123456"))
def CharToStr(hex_num):
'''输入十六进制,输出十进制ascii对应的字符'''
return chr(int(hex_num,16))
# print(CharToStr("2c"))
def ToStr(string):
'''Hex转Str'''
result = ""
lis = GetList(string.replace("0x",""))
for i in lis:
result += CharToStr(i)
return result
# print(ToStr("28372c37"))
def FileToStr(path,save):
'''读取Hex文件,输出Str结果'''
result = ""
with open(path,"r") as fp:
string = fp.read().replace("\\n","")
lis = GetList(string.replace("0x", ""))
for i in lis:
result += CharToStr(i)
with open(save,"w") as fp:
fp.write(result)
# FileToStr("1.txt","2.txt")
def CharToHex(string):
'''输入字符,输出十六进制,不支持输入字符串'''
return str(hex(ord(string))).replace("0x", "")
# print(CharToHex(","))
def ToHex(string):
'''Str转Hex'''
result = ""
for i in string:
result += CharToHex(i)
return result
# print(ToHex("7"))
def FileToHex(path,save):
'''读取Str文件,输出Hex结果'''
result = ""
with open(path, "r") as fp:
string = fp.read().replace("\\n", "")
for i in string:
result += CharToHex(i)
with open(save, "w") as fp:
fp.write(result)
# FileToHex("3.txt","4.txt")
if __name__ =='__main__':#主函数
while True:
print("==============================")
print(" 0. 退出")
print(" 1. Hex转Str")
print(" 2. Hex转Str(文件读取)")
print(" 3. Str转Hex")
print(" 4. Str转Hex(文件读取)")
print("==============================")
flag = int(input("请选择:"))
if flag==1:
Hex = input("Hex:")
print("Str:\\n",ToStr(Hex))
elif flag==2:
Hex_path = input("Hex文件路径:")
Save_path = input("Str保存路径:")
FileToStr(Hex_path,Save_path)
print("处理结束!")
elif flag==3:
Str = input("Str:")
print("Hex:\\n",ToHex(Str))
elif flag==4:
Str_path = input("Str文件路径:")
Save_path = input("Hex保存路径:")
FileToHex(Str_path,Save_path)
print("处理结束!")
else:
break
以上是关于Python-十六进制与字符串转换脚本的主要内容,如果未能解决你的问题,请参考以下文章
在 Python 中将二进制数组转换为十进制(相当于 R readBin?)