【问题标题】:hexadecimal to strings using python使用python的十六进制字符串
【发布时间】:2022-11-03 11:36:13
【问题描述】:

我是 python 新手,正在尝试将十六进制列表转换为字符串

chunk= [' ho', 'w a', 're ', 'you']
chunk_2 = [i.encode('utf-8').hex() for i in chunk]
print(chunk_2)
['20686f', '772061', '726520', '796f75']

chunk_3 = [int(i, base=16) for i in chunk_2]
print(chunk_3)
[2123887, 7807073, 7496992, 7958389]
(convert chunk_3 to hexadecimal)

chunk_4 = [f'{i:x}' for i in chunk_3]
print (chunk_4)
['20686f', '772061', '726520', '796f75']

if my message is
print(mess_age)
[2795630699, 2632110001, 2129175822, 2593136416]

chunk_4 = [f'{i:x}' for i in mess_age]
print(chunk_4)
['a6a1f06b', '9ce2cfb1', '7ee8a50e', '9a901f20']

decrypted_message = [bytes.fromhex(i).decode('utf-8') for i in chunk_4]

"UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa6 in position 0: invalid start byte"

你能告诉我为什么这个错误

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以为此使用字节数组。

    >>> chunk_4 = ['20686f', '772061', '726520', '796f75']
    >>> [bytes.fromhex(k).decode() for k in chunk_4]
    [' ho', 'w a', 're ', 'you']
    

    【讨论】:

    • bytes.fromhex 可能更常见,因为我们在这里不需要可变字节数组。
    • 好点子。我的 Google 搜索找到了 bytesarray 示例,所以我只是复制了它。
    • @TimRoberts 请检查一下我为什么会出错(UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf9 in position 2: invalid start byte)
    • 这表示您正在尝试翻译不在 UTF-8 中的字符串。您可以删除 .decode() 以查看 8 位版本。如果您知道您期望它是什么字符,您可以弄清楚您正在使用什么代码页以及如何进行解码。
    猜你喜欢
    • 2023-04-08
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 2013-08-05
    • 2010-10-04
    • 2015-05-30
    • 2011-01-21
    相关资源
    最近更新 更多