Python - How To String to Hex in Python

ID : 96

viewed : 113

Tags : PythonPython StringPython Hex

vote vote


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,

a = 102 print(hex(a)) 



We can also convert float values to hexadecimal using the hex() function with the float() function. The following code implements this.

a = 102.18 print(float.hex(a)) 



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.

For example,

s= 'Sample String'.encode('utf-8') print(s.hex()) 



In the above code, we encode the string in the utf-8 type and convert it into byte types.

  • Related HOW TO?