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
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") .
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.
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.
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.
In python 3x Use binascii
instead of hex:
>>> import binascii
>>> binascii.hexlify(b'< character / string>')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With