How do I convert a single character into its hex ASCII value in Python?

How do I convert a single character into its hex ASCII value in Python?

There are several ways of doing this:

>>> hex(ord(c))
0x63
>>> format(ord(c), x)
63
>>> import codecs
>>> codecs.encode(bc, hex)
b63

On Python 2, you can also use the hex encoding like this (doesnt work on Python 3+):

>>> c.encode(hex)
63

This might help

import binascii

x = btest
x = binascii.hexlify(x)
y = str(x,ascii)

print(x) # Outputs b74657374 (hex encoding of test)
print(y) # Outputs 74657374

x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs btest

x_ascii = str(x_unhexed,ascii)
print(x_ascii) # Outputs test

This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line youd want to use is str(binascii.hexlify(c),ascii).

How do I convert a single character into its hex ASCII value in Python?

Considering your input string is in the inputString variable, you could simply apply .encode(utf-8).hex() function on top of this variable to achieve the result.

inputString = Hello
outputString = inputString.encode(utf-8).hex()

The result from this will be 48656c6c6f.

Leave a Reply

Your email address will not be published. Required fields are marked *