Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the 'hex' encoding in Python 3.2 or higher?

In Python 2, to get a string representation of the hexadecimal digits in a string, you could do

>>> '\x12\x34\x56\x78'.encode('hex') '12345678' 

In Python 3, that doesn't work anymore (tested on Python 3.2 and 3.3):

>>> '\x12\x34\x56\x78'.encode('hex') Traceback (most recent call last):   File "<stdin>", line 1, in <module> LookupError: unknown encoding: hex 

There is at least one answer here on SO that mentions that the hex codec has been removed in Python 3. But then, according to the docs, it was reintroduced in Python 3.2, as a "bytes-to-bytes mapping".

However, I don't know how to get these "bytes-to-bytes mappings" to work:

>>> b'\x12'.encode('hex') Traceback (most recent call last):   File "<stdin>", line 1, in <module> AttributeError: 'bytes' object has no attribute 'encode' 

And the docs don't mention that either (at least not where I looked). I must be missing something simple, but I can't see what it is.

like image 906
Tim Pietzcker Avatar asked Oct 16 '12 14:10

Tim Pietzcker


People also ask

How do I encode a hex in python?

To convert Python String to hex, use the inbuilt hex() method. The hex() is a built-in method that converts the integer to a corresponding hexadecimal string. For example, use the int(x, base) function with 16 to convert a string to an integer.

How do you encode a hexadecimal?

Hex encoding is performed by converting the 8 bit data to 2 hex characters. The hex characters are then stored as the two byte string representation of the characters. Often, some kind of separator is used to make the encoded data easier for human reading.

How do you assign a hex value to a variable in Python?

To assign value in hexadecimal format to a variable, we use 0x or 0X suffix. It tells to the compiler that the value (suffixed with 0x or 0X) is a hexadecimal value and assigns it to the variable.


2 Answers

You need to go via the codecs module and the hex_codec codec (or its hex alias if available*):

codecs.encode(b'\x12', 'hex_codec') 

* From the documentation: "Changed in version 3.4: Restoration of the aliases for the binary transforms".

like image 140
ecatmur Avatar answered Oct 01 '22 03:10

ecatmur


Yet another way using binascii.hexlify():

>>> import binascii >>> binascii.hexlify(b'\x12\x34\x56\x78') b'12345678' 
like image 26
Mark Tolonen Avatar answered Oct 01 '22 03:10

Mark Tolonen