66

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?

dda
  • 6,030
  • 2
  • 25
  • 34
IamPolaris
  • 1,021
  • 2
  • 10
  • 19

5 Answers5

115

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'
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 13
    `"{0:02x}".format(ord('c'))` keeps the leading zero, if there is one. – Mike DeSimone Nov 11 '11 at 00:56
  • @eryksun: On Python 3, you can use `binascii.hexlify()` and `binascii.unhexlify()` instead. – Sven Marnach Nov 11 '11 at 14:02
  • Using a capital `X` for the format string will use uppercase A-F digits, if that is preferred. See [the docs](https://docs.python.org/2/library/string.html#format-specification-mini-language) for details. – Michael Mar 23 '17 at 13:24
  • On Python 3 using "c".encode("hex") will raise "LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs" – Nagev Sep 27 '17 at 12:34
  • 1
    @Nagev bytes-to-bytes encoding need to be invoked via the `codecs` module in Python 3: `codecs.encode(b"c", "hex")` – Sven Marnach Sep 27 '17 at 12:38
  • interesting answer, but you're not converting a character to hex, you're converting a byte to hex, which is already easy to do in several different ways? – simpleuser May 26 '20 at 16:24
  • @simpleuser I'm not sure I understand what "converting a character to hex" means. This answer wass originally written for Python 2, and characterrs and bytes were kind of the same at the time. Moreover, several of these methods work fine for arbitrrary Unicode characters, e.g. `hex(char("c"))` will convert the Unicode codepoint of the given character to hex. – Sven Marnach May 26 '20 at 19:19
8

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

Joundill
  • 6,828
  • 12
  • 36
  • 50
James Peters
  • 147
  • 1
  • 9
  • Hi, and welcome to StackOverflow. I am confused by the comments in your code (e.g. `# x -> b'test'`). I don't see where "test" is used anywhere in the source. I also think it would be help to format the output as a code block as well, to preserve newlines. – Michael Mar 23 '17 at 13:29
  • `b'test'` is used on the very next line. All he is saying is that x is the string 'test' but the `b` in front signals that it is to be in a bytes format. The next line hexlify's these bytes into a new value – Reedinationer Jan 26 '19 at 04:51
  • note that hexlify seems to output the value as string, hence a single char will be converted to 2 chars(namely the numerical values), which for me was a big problem since i had very limited space on a embedded device (a mifare card) – clockw0rk Jun 06 '19 at 14:45
5

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.

Sarath Subramanian
  • 20,027
  • 11
  • 82
  • 86
3

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

Mtamred
  • 51
  • 4
1

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