Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode Hex String in Python 3

In Python 2, converting the hexadecimal form of a string into the corresponding unicode was straightforward:

comments.decode("hex") 

where the variable 'comments' is a part of a line in a file (the rest of the line does not need to be converted, as it is represented only in ASCII.

Now in Python 3, however, this doesn't work (I assume because of the bytes/string vs. string/unicode switch. I feel like there should be a one-liner in Python 3 to do the same thing, rather than reading the entire line as a series of bytes (which I don't want to do) and then converting each part of the line separately. If it's possible, I'd like to read the entire line as a unicode string (because the rest of the line is in unicode) and only convert this one part from a hexadecimal representation.

like image 420
chimeracoder Avatar asked Jul 19 '10 18:07

chimeracoder


People also ask

How do you decode a hex string in Python?

The easiest way to convert hexadecimal value to string is to use the fromhex() function. This function takes a hexadecimal value as a parameter and converts it into a string. The decode() function decodes bytearray and returns a string in utf-8 format.

How do you decode a hex encoded string?

If you want to decode hex that represents bytes (for example an encryption key), try the Text → Bytes step in hex mode instead. Note this is not a strict hex decoder. It will simply strip any characters from your input that are not in the hex character set (0-9, A-F) and decode what's left. The result may be garbled.

How do I read hex data in Python?

hex() function in Python hex() function is one of the built-in functions in Python3, which is used to convert an integer number into it's corresponding hexadecimal form. Syntax : hex(x) Parameters : x - an integer number (int object) Returns : Returns hexadecimal string.

How do I decode in Python 3?

Python 3 - String decode() MethodThe decode() method decodes the string using the codec registered for encoding. It defaults to the default string encoding.


2 Answers

Something like:

>>> bytes.fromhex('4a4b4c').decode('utf-8') 'JKL' 

Just put the actual encoding you are using.

like image 109
unbeli Avatar answered Sep 21 '22 10:09

unbeli


import codecs  decode_hex = codecs.getdecoder("hex_codec")  # for an array msgs = [decode_hex(msg)[0] for msg in msgs]  # for a string string = decode_hex(string)[0] 
like image 43
Niklas Avatar answered Sep 25 '22 10:09

Niklas