Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 - How to convert a string to hex

I am trying to convert a string to hex character by character, but I cant figure it out in Python3.

In older python versions, what I have below works:

test = "This is a test"
for c in range(0, len(test) ):
   print( "0x%s"%string_value[i].encode("hex") )

But with python3 I am getting the following error:

LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs.

Can anyone help to tell me what the conversion would be in python3.

Thanks in advance

like image 489
Godspped Avatar asked Aug 12 '16 03:08

Godspped


People also ask

How do I convert a string to a number in Python 3?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

How do I convert a string to a string in Python?

The str() function takes in any python data type and converts it into a string. But use of the str() is not the only way to do so. This type of conversion can also be done using the “%s” keyword, the .format function or using f-string function.

What is a string that starts with 0x?

The hexadecimal system can represent much larger numbers using fewer characters, and it closely resembles binary numbers. Hexadecimal numbers are usually prefixed with the characters '0x' which are not part of the number.

How do you represent hexadecimal in Python?

When denoting hexadecimal numbers in Python, prefix the numbers with '0x'. Also, use the hex() function to convert values to hexadecimal format for display purposes.


1 Answers

In python 3x Use binascii instead of hex:

>>> import binascii
>>> binascii.hexlify(b'< character / string>')
like image 125
Tony Vincent Avatar answered Sep 22 '22 22:09

Tony Vincent