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?
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.
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.
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.
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')
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With