因为工作需要,在处理数据中需要对报文需要解析,所系就要把十六进制的数据进行转换,可以打包成exe方便使用
[Python] 纯文本查看 复制代码 #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project :pythonproject
@file :十六进制数据转换.py
@IDE :PyCharm
@AuThor :海绵的烂笔头
@date :2023-07-20 11:54
'''
import struct
def hex_to_data(hex_str, endian='little'):
# 将十六进制字符串转换为bytes对象
hex_bytes = bytes.fromhex(hex_str)
# 根据字节序重新排序bytes对象
if endian == 'big':
hex_bytes = hex_bytes[::-1]
data = {}
# 浮点数
if len(hex_bytes) == 4:
data['float'] = struct.unpack('f', hex_bytes)[0]
# 双精度浮点数
elif len(hex_bytes) == 8:
data['double'] = struct.unpack('d', hex_bytes)[0]
# 整数(32位或64位)
if len(hex_bytes) == 4:
data['int32'] = struct.unpack('i', hex_bytes)[0]
elif len(hex_bytes) == 8:
data['int64'] = struct.unpack('q', hex_bytes)[0]
# 转换为二进制字符串
binary_str = bin(int.from_bytes(hex_bytes, byteorder='big'))[2:]
data['binary'] = binary_str
# 转换为十进制数值
decimal_value = int(hex_str, 16)
data['decimal'] = decimal_value
return data
if __name__ == "__main__":
hex_data = input("请输入十六进制数据:")
endian_choice = input("请选择字节序(输入 'little' 或 'big'):")
try:
result = hex_to_data(hex_data, endian=endian_choice)
print("转换结果:")
for key, value in result.items():
print(f"{key}: {value}")
except ValueError as e:
print("转换错误:", e)
|