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

PythonHexAscii

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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'

Solution 2 - Python

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').

Solution 3 - 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.

Solution 4 - Python

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

Solution 5 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIamPolarisView Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow
Solution 2 - PythonJames PetersView Answer on Stackoverflow
Solution 3 - PythonSarath KSView Answer on Stackoverflow
Solution 4 - PythonMattView Answer on Stackoverflow
Solution 5 - Pythonf180362 Asad UllahView Answer on Stackoverflow