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