- Convert String to Hex in Python
- Decode the value back to a string
- How To Convert String To Hexadecimal Number in Python
- Table of Contents
- String to Hex
- Using encode()
- Using ast library method
- Using the hex() method
- Using binascii
- Hex to String
- Using decode() method
- Using codecs.decode() method
- By appending hex to a string
- Using the binascii module
- Hex to integer
- Conclusion
- Tanner Abraham
- How to convert a Python string to Hex format?
- # 1: Using the int() function:
- # 2: Using ast.literal_eval() function:
- Print string as bytes in Python
- Follow up learning
- Recent Posts
- String to Hex in Python
- Related Article — Python String
- Related Article — Python Hex
Convert String to Hex in Python
The hex() function can be used to convert a string to a hexadecimal value. Before using the function the value has to be converted to bytes.
The value is returned as a string representing a hexadecimal value.
Split these values into hex numbers:
You can see, how are these values calculated.
Hex | Dec | Operation | ASCII |
0x68 | 104 | 6*16^1 + 8*16^0 = 6*16 + 8 * 1 = 104 | h |
0x65 | 101 | 6*16^1 + 5*16^0 = 6*16 + 5 * 1 = 101 | e |
0x6c | 108 | 6*16^1 + 12*16^0 = 6*16 + 12 * 1 = 108 | l |
0x6c | 108 | 6*16^1 + 12*16^0 = 6*16 + 12 * 1 = 108 | l |
0x6f | 111 | 6*16^1 + 15*16^0 = 6*16 + 15 * 1 = 111 | o |
Decode the value back to a string
If you want to decode this hex string into a string, you can use the following code, or read this tutorial.
How To Convert String To Hexadecimal Number in Python
In this tutorial you will learn how to convert a string to hex in Python, and a hex to string in Python.
Table of Contents
String to Hex
There exist different methods of converting a string into a hex in python.
Hexadecimal values have a base of 16, and the prefix 0x is used to display any given string in hexadecimal format. Strings can be converted into a hexadecimal format in one of the following ways.
Using encode()
The encode() method is one of the most popular methods of converting any string into hex format. In this method, firstly string is converted into bytes using the encode() method, and then the resulting value is converted into hex format using the hex method.
# Converting a string into bytes using encode method string = "Converting string into hex format.".encode('utf-8') # Using the hex method to convert the bytes into hexadecimal format string.hex() # Printing the hexadecimal value of the given string print(string.hex())
436f6e76657274696e6720737472696e6720696e746f2068657820666f726d61742e
Using ast library method
In this method, the ast library is used to convert a given string into hex format. Firstly, literal_eval is imported from the ast library. Secondly, a string is created with the prefix 0x because this method only accepts the characters with 0x prefixes.
After making the string, it is passed through the literal_eval method. This method gives the integer format of the given string, which can then be passed through the hex method to obtain the hex value of the given string.
# Importing literal_eval from ast library from ast import literal_eval string = "0x569" # Converting a string into an integer using literal_eval method str_into_int = literal_eval(string) # Passing integer value through hex method hex_value = hex(str_into_int) # Printing the hex value print(hex_value)
Using the hex() method
hex() method is generally used to convert the hexadecimal integers string value to hexadecimal values. In this method, a hexadecimal integer is passed as a parameter through the hex() method, and it provides the hexadecimal value of the given string.
For this method to work, the given string should be converted into a hexadecimal integer value, and then the integer value should be passed through the hex function.
Any given string can be converted into a hexadecimal integer value by passing it through the int method along with the base 16 as a parameter.
hex_string = "0x64533490" # Passing the string through the int method with base 16 to convert it into an integer int_format = int(hex_string, 16) # Passing the integer value through the hex method hex_format = hex(int_format) # Print the hexadecimal format of the integer print(hex_format)
Sometimes you will encounter syntax errors and typeErrors because the hex method only accepts integer values and if you pass a string through it, then it will give an error.
Another fastest way of converting a string into a hexadecimal value is using b with hex method. In this method, “b” is placed at the beginning of a string which indicates the conversion of the string into bytes.
Generally, hex values start with 0x, so the prefix “0x” can be placed with the output to get the hexadecimal value of any given string.
print("0x"+ converting string into hex format".hex())
0x436f6e76657274696e6720737472696e6720696e746f2068657820666f726d6174
Using binascii
In this method, binascii library is used to convert any given string into hex format.
Firstly, we import the binascii module. Secondly, the given string is converted into a byte object using b.
Finally, the byte object is passed through the hexlify method, which gives the hex value of the given string.
# Importing library import binascii # Using b to convert the string into bytes string = b"Hello" # Using the hexlify method to convert bytes into hexadecimal format print(binascii.hexlify(string))
If the purpose is just to convert the strings of the alphabet into the hexadecimal format, then the ord method along with the hex method can be applied to get the hex value of any given alphabet.
print(hex(ord("a"))) print(hex(ord("T")))
=> Join the Waitlist for Early Access.
By subscribing, you agree to get emails from me, Tanner Abraham. I’ll respect your privacy and you can unsubscribe any time.
Hex to String
Hexadecimal string and ASCII values in python are interchangeable and different methods can be used to convert a given hex value to a string and vice versa.
Using decode() method
In this method, bytearray.decode (encoding, error) takes the byte array as an input and then decodes it using the encoding specified as an argument.
In order to decode a hex value, the first step is to convert the hex string into a byte string and then apply the bytearray.decode() method.
To convert hex string into bytes, bytearray.fromhex() method can be used.
# Converting hex value to a string string = "68656c6c6f" # Using fromhex method from bytearray to convert hex value to byte byte_array = bytearray.fromhex(string) # Using decode method to convert bytes into ASCII string byte_array.decode() # Printing the string print(byte_array.decode())
Using codecs.decode() method
In this method, codecs module is imported to convert the hex values into strings. This method requires a codecs library for conversion, which contains base classes for encoding and decoding data, commonly used in Unicode text-based files.
This method is similar to the decode() method. The only difference is that along with encoding and error arguments, this method also takes the objects as input arguments.
Error argument in this method is used to handle errors during the execution of the program. The codecs.decodes() method in this case returns a byte object, which is then converted into the string using the str() method.
# Importing the codecs library import codecs # The hexadecimal string string = "68656c6c6f" # Converting the hex string into bytes using the codecs.decode() method binary_str = codecs.decode(string, "hex") # Converting the resultant byte into the string str(binary_str,'utf-8') # Printing out the string print(str(binary_str,'utf-8'))
By appending hex to a string
In this method, a hex value is converted into a string and then combined with the other string. It’s an efficient one-liner that reads in a single hex value at a time converts it to an ASCII character and appends it to the end of the variable.
This repeats until the conversion is complete.
def hex_to_str(hex): if hex[:2] == '0x': hex = hex[2:] str_value = bytes.fromhex(hex).decode('utf-8') return str_value hex_value = '0x737472696e67' print(hex_value) string = 'Converting hex to ' + hex_to_str('737472696e67') print(string)
Using the binascii module
It is one of the simplest ways of converting a hex value to a string format. In this method, the unhexlify method of the binascii module is used for the conversion of hex value to string format.
# Importing binascii module import binascii # Using unhexlify method from binascii module binascii.unhexlify('737472696e67') # Printing the output print(binascii.unhexlify('737472696e67'))
Hex to integer
The int constructor int() can be used for conversion between a hex string and an integer. The int constructor takes the string and the base you are converting from and will give the corresponding integer value of given hex.
hex_value = "0x64" x = int(hex_value, 0) print(x)
Conclusion
There are many ways to convert strings to hexadecimals, and hexadecimals to strings in Python. A practical use case for these conversion methods could be obtaining character codes being read in from files.
Tanner Abraham
Data Scientist and Software Engineer with a focus on experimental projects in new budding technologies that incorporate machine learning and quantum computing into web applications.
=> Join the Waitlist for Early Access.
By subscribing, you agree to get emails from me, Tanner Abraham. I’ll respect your privacy and you can unsubscribe any time.
How to convert a Python string to Hex format?
You can use one of the following two methods to convert and print a python string as an hexadecimal:
- Convert the Python string to an integer, using the int() function, and then convert to an hexadecimal using hex().
- Turn the string to an integer using the literal_eval function (from the ast Python module) and then cast to hexadecimal.
# 1: Using the int() function:
Using int(string, base=16) , we can convert the string to an integer with base 16 (Hexadecimal). Once we have the integer, we can use the inbuilt hex() function to convert an integer to a Hexadecimal number. So when we get a string, we will initially convert the string to an integer. We will then convert the integer value to hexadecimal using the function hex(). Let us see it in action.
def get_hex(value): convert_string = int(value, base=16) convert_hex = hex(convert_string) return convert_hex, convert_string userstring = "0XABC" convert_hex, convert_string = get_hex(userstring) print("String to Integer:",convert_string) print("Integer to Hex:",convert_hex)
String to Integer: 2748 Integer to Hex: 0xabc
# 2: Using ast.literal_eval() function:
Using the literal_eval from the ast library, we can easily get the string and convert it to an integer. Then we can use the hex() function to get the Hexadecimal value. All we have to do is that we will need to import the literal_eval function from ast. Let us look at an example.
from ast import literal_eval def get_hex(value): convert_string = literal_eval(value) convert_hex = hex(convert_string) return convert_hex, convert_string userstring = "0xabc" convert_hex, convert_string = get_hex(userstring) print("String to Integer:",convert_string) print("Integer to Hex:",convert_hex)
String to Integer: 2748 Integer to Hex: 0xabc
Print string as bytes in Python
In order to cast and print a Python string to bytes, use the bytes() function, as shown in the code below:
file_str = 'Python string object' print (bytes (file_str, encoding='windows-1255'))
Note: Use the decode() function to turn bytes to a string object.
Follow up learning
Recent Posts
String to Hex in Python
Hexadecimal values have a base of 16. In Python, hexadecimal strings are prefixed with 0x .
The hex() function is used to convert a decimal integer to its respective hexadecimal number. For example,
We can also convert float values to hexadecimal using the hex() function with the float() function. The following code implements this.
We cannot convert a string using this function. So if we have a situation where we have a hexadecimal string and want to convert it into the hexadecimal number, we cannot do it directly. For such cases, we have to convert this string to the required decimal value using the int() function and then convert it to the hexadecimal number using the hex() function discussed earlier.
The following code shows this.
hex_s = '0xEFA' a = int(hex_s,16) hex_n = hex(a) print(hex_n)
Characters in the string do not have any corresponding hexadecimal value. However, if we convert a string to a bytes type object, using the encode() function, we can convert it to its hexadecimal value using the hex() function.
s= 'Sample String'.encode('utf-8') print(s.hex())
53616d706c6520537472696e67
In the above code, we encode the string in the utf-8 type and convert it into byte types.
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
Related Article — Python String
Related Article — Python Hex
Copyright © 2023. All right reserved