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

Question:

I am interested in taking in a single character.

c = 'c' # for example
hex_val_string = char_to_hex_string(c)
print hex_val_string

output:

63

What is the simplest way of going about this? Any predefined string library stuff?

Asked By: IamPolaris

||

Answers:

There are several ways of doing this:

>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'

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

>>> "c".encode("hex")
'63'
Answered By: Sven Marnach

This might help

import binascii

x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')

print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374

x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'

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 you’d want to use is str(binascii.hexlify(c),'ascii').

Answered By: James Peters

to get ascii code use ord("a");
to convert ascii to character use chr(97)

Answered By: f180362 Asad Ullah

You can do this:

your_letter = input()
def ascii2hex(source):
    return hex(ord(source))
print(ascii2hex(your_letter))

For extra information, go to:
https://www.programiz.com/python-programming/methods/built-in/hex

Answered By: Matt

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.

Answered By: Sarath Subramanian
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.