To convert string to hex in Python, use the hex() method. The hex() is a built-in method that converts the integer to a corresponding hexadecimal string.
You can use the int(x, base) function with 16 to convert a string to an integer.
Hex strings have a “0x” prefix. In Python, if you have a “0x” prefix and a valid string, use the int(string, 0) method to get the integer. The 0 is provided to tell the function to interpret the base from the prefix.
Syntax of hex()
hex(n)
Parameters
The hex() method takes one required argument n: integer number.
Return Value
The hex() method converts an integer to a corresponding hexadecimal number in the string form and returns it. The returned hexadecimal string starts with the prefix 0x, indicating it’s in the hexadecimal format.
Example of converting a string to hex
hex_string = "0xFF" an_integer = int(hex_string, 16) hex_value = hex(an_integer) print(hex_value)
Output
0xff
You can see from the output that the returned string is hexadecimal because it starts with 0xff.
Python hex() with object
Convert a Python object into a hash value using the hex() method.
Create a custom class and define the __index__() function to use the hex() function with it.
class Ditto: no = 0 def __index__(self): print('__index__ function called') return self.no dt = Ditto() dt.no = 19 print(hex(dt))
Output
__index__ function called 0x13
Hexadecimal representation of a float
Use float.index() method to convert float to hex.
number = 0.0 print(number, "in hex =", float.hex(number)) number = 19.5 print(number, "in hex =", float.hex(number))
Output
0.0 in hex = 0x0.0p+0 19.5 in hex = 0x1.3800000000000p+4
Errors and Exceptions to convert string to hex.
The hex() function throws a TypeError when anything other than integer type constants is passed as parameters.
hex_string = "0xFF" hex_value = hex(hex_string) print(hex_value)
Output
TypeError: 'str' object cannot be interpreted as an integer
You can see that the hex() function always expects an integer, but it gets a string, which is why it throws an error.
The hex() method is used in all the standard conversions, like converting hexadecimal to decimal, hexadecimal to octal, and hexadecimal to binary.
Conclusion
To convert a hex string (ex: 0xAD4) to a hex number, use the hex() function.
Use the int() function with the second parameter, 16, to convert a hex string to an integer. Then, the hex() function converts it to a hexadecimal number.
That’s it for this article.