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.

print(bytes.fromhex('68656c6c6f').decode('utf-8'))

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:

print(b'hello'.hex())

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).

import codecs

my_string = "68656c6c6f"
my_string_bytes = bytes(my_string, encoding='utf-8')

binary_string = codecs.decode(my_string_bytes, "hex")
print(str(binary_string, 'utf-8'))

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 return it as a string.

def hex_to_string(hex):
    if hex[:2] == '0x':
        hex = hex[2:]
    string_value = bytes.fromhex(hex).decode('utf-8')
    return string_value

hex_value = '0x737472696e67'
string = 'This is just a ' + hex_to_string('737472696e67')

print(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