简体   繁体   中英

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

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

I don't know python well, it's like my first time using python 3. Here's the code:

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?

You are getting this error because 0x91 , or 145 in decimal, is not a valid ascii value.

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.

hex_ = "74 69 6d 65 73 74 61 6D 70"

s = ''.join([chr(int(x, 16)) for x in hex_.split()])

print(s)

Output

timestamp

As a sidenote, avoid using hex as a variable since it overwrites the builtin function hex .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM