Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

hex

ascii

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?

like image 868
IamPolaris Avatar asked Nov 11 '11 00:11

IamPolaris


People also ask

How do you convert a character to ASCII in Python?

chr () is a built-in function in Python that is used to convert the ASCII code into its corresponding character. The parameter passed in the function is a numeric, integer type value. The function returns a character for which the parameter is the ASCII code.

How do you change the ASCII value of a character?

Very simple. Just cast your char as an int . char character = 'a'; int ascii = (int) character; In your case, you need to get the specific Character from the String first and then cast it.

Can you convert string to hex in Python?

To convert Python String to hex, use the inbuilt hex() method. The hex() is a built-in method that converts the integer to a corresponding hexadecimal string. For example, use the int(x, base) function with 16 to convert a string to an integer.


3 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' 
like image 178
Sven Marnach Avatar answered Oct 13 '22 07:10

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

like image 40
James Peters Avatar answered Oct 13 '22 08:10

James Peters


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.

like image 25
Sarath KS Avatar answered Oct 13 '22 08:10

Sarath KS