HEX decoding in Python 3.2

In Python 2.x, I can do this:

>>> '4f6c6567'.decode('hex_codec') 'Oleg' 

But in Python 3.2, I ran into 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) 

According to docs, hex_codec should contain "byte to byte mappings." Thus, the byte string object is correctly used here.

How can I get rid of this error to avoid cumbersome workarounds for converting from hex encoded text?

+7
source share
1 answer

In Python 3, the bytes.decode() method is used to decode raw bytes in Unicode, so you should 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.

You can also look at binascii.unhexlify() .

+10
source

All Articles