Python 3.2中的HEX解码 [英] HEX decoding in Python 3.2
问题描述
在Python 2.x中,我可以执行以下操作:
In Python 2.x I'm able to do this:
>>> '4f6c6567'.decode('hex_codec')
'Oleg'
但是在Python 3.2中我遇到此错误:
But in Python 3.2 I encounter this error:
>>> b'4f6c6567'.decode('hex_codec')
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
b'4f6c6567'.decode('hex_codec')
TypeError: decoder did not return a str object (type=bytes)
根据 docs hex_codec
应该提供字节到字节的映射。因此,这里正确使用了字节字符串的对象。
According to the docs hex_codec
should provide "bytes-to-bytes mappings". So the object of byte-string is correctly used here.
如何摆脱此错误,才能避免繁琐的变通方法从十六进制编码的文本转换?
How can I get rid of this error to be able to avoid unwieldy workarounds to convert from hex-encoded text?
推荐答案
在Python 3中, bytes.decode()
方法是用于将原始字节解码为Unicode,因此必须使用 codecs.getdecoder()
codecs 模块获取解码器>或 codecs.decode()
到字节
到字节
编码:
In Python 3, the bytes.decode()
method is used to decode raw bytes to Unicode, so you have to get the decoder from the codecs
module using codecs.getdecoder()
or codecs.decode()
for bytes
-to-bytes
encodings:
>>> codecs.decode(b"4f6c6567", "hex_codec")
b'Oleg'
>>> codecs.getdecoder("hex_codec")(b"4f6c6567")
(b'Oleg', 8)
文档中似乎缺少后一个功能,但是有一个有用的文档字符串。
The latter function seems to be missing from the documentation, but has a useful docstring.
您可能还想看看 binascii.unhexlify()
。
这篇关于Python 3.2中的HEX解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!