Convert Hex to String in Python

This is a tutorial on how to convert hexadecimal numbers to strings in Python. When working with hex numbers, it can be difficult to read or compare them, so converting them to strings will make the process easier.

The easiest way to convert hexadecimal value to string is to use the fromhex() function.

This function takes a hexadecimal value as a parameter and converts it into a string. The decode() function decodes bytearray and returns a string in utf-8 format.

hello

Notice that in the string there are only numbers from 0 to 9 and letters from “a” to “f”. If you put any other letter, Python will return the error:

ValueError: non-hexadecimal number found in fromhex() arg at position 0

You can quickly convert this string back to hex using this code:

There must be “b” at the beginning of the string indicating that the value is converted to bytes.

How this conversion works

If you split this string into individual values, you will get:

0x68 0x65 0x6c 0x6c 0x6f

“0x”  at the beginning means that the value should be treated as a hexadecimal value.

This table shows how each value is converted to a letter.

HexDecOperationASCII
0x681046*16^1 + 8*16^0 = 6*16 + 8 * 1 = 104h
0x651016*16^1 + 5*16^0 = 6*16 + 5 * 1 = 101e
0x6c1086*16^1 + 12*16^0 = 6*16 + 12 * 1 = 108l
0x6c1086*16^1 + 12*16^0 = 6*16 + 12 * 1 = 108l
0x6f1116*16^1 + 15*16^0 = 6*16 + 15 * 1 = 111o

Using codecs.decode

The codecs.decode is another method you can use to achieve the same result. It takes three arguments: the bytes object, encoding, and error (specifies how errors should be handled).

The my_string_bytes variable converts a string to bytes using utf-8. Now, this variable can be passed as the first argument. The second argument is “hex” as we want to convert the hex value to a string.

This code returns the same string as before:

hello

Append hex to string

To append a hexadecimal value to a string, first, you have to convert it and then use it to join these two strings.

For this, we are going to use a function that converts hex to string and returns it as a string.

Sometimes the hex value can be preceded by “0x”. Our function checks whether this is a case and removes these two characters from the string.

Because the function returns a string value, it can be appended to another string.

This is the returned value.

This is just a string