[英]Converting hex to string in python
I'm trying to convert an hex value to string but i keep getting this error我正在尝试将十六进制值转换为字符串,但我不断收到此错误
Traceback (most recent call last): File
回溯(最近一次通话):文件
"C:\\Users\\ASUS\\Desktop\\parse.py", line 14, in
“C:\\Users\\ASUS\\Desktop\\parse.py”,第 14 行,在
data = bytes.fromhex(''.join(map(str,tup[4:4+length]))).decode("utf8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x91 in position 0: invalid start byte
UnicodeDecodeError: 'utf-8' 编解码器无法解码位置 0 中的字节 0x91:起始字节无效
I don't know python well, it's like my first time using python 3. Here's the code:我不是很了解python,就像我第一次使用python 3。代码如下:
import binascii
import struct
hex ="01 06 1C 02 5B 90 10 6F 01 03 3C 04 01 01 03 07 01 00 01 03 07 1E 01 01 09 05 15 00 00 04 54 52 2D 31 01 11 05 02 00 00 00 00 00 01 01 00 00 00 00 00 00 00 00 01 27 01 01 00 23 08 09 01 2A 41 73 64 23 31 23 31 23 30 23 31 30 30 30 23 30 23 30 2C 30 2C 30 23 30 23 23 30 23 23 23 30 01 04 05 16 00 28 01 03 05 0A 00 01 09 01 01 00 05 08 15 01 31 01 01 06 01 01 00 02 05 07 "
p1 = binascii.unhexlify(''.join(hex.split()))
print(p1)
print("\n\n")
tup = struct.unpack(str(len(p1))+'B', p1)
if tup[0] == 1:
# <= 0xFF
length = tup[1] - 2
C = tup[2]
CC = tup[3]
print("C: "+str(C)+", CC: "+str(CC)+" Size: "+str(length))
nHex = ''.join(map(str,tup[4:4+length]))
# code below is from another stackoverflow answer and can be replaced if you got a better one
data = bytes.fromhex(nHex).decode("utf8")
print("".join(chr(c) if chr(c) in string.printable else '.' for c in data))
I should get a timestamp as a string after decoding the hex.解码十六进制后,我应该得到一个时间戳作为字符串。 How can I convert
nHex
to string?如何将
nHex
转换为字符串?
You are getting this error because 0x91
, or 145
in decimal, is not a valid ascii value.您收到此错误是因为
0x91
或十进制145
不是有效的 ascii 值。
You can use int(_, 16)
to convert an hexadecimal string to its integer value and then chr
to convert this integer to the corresponding unicode character.您可以使用
int(_, 16)
将十六进制字符串转换为其整数值,然后使用chr
将此整数转换为相应的unicode字符。
hex_ = "74 69 6d 65 73 74 61 6D 70"
s = ''.join([chr(int(x, 16)) for x in hex_.split()])
print(s)
timestamp
As a sidenote, avoid using hex
as a variable since it overwrites the builtin function hex
.作为旁注,避免使用
hex
作为变量,因为它会覆盖内置函数hex
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.