4 Pythonic Ways to Convert from HEX to ASCII

Rate this post

Problem Formulation and Solution Overview

In this article, you’ll learn how to convert HEX values to an ASCII string in Python.

To make it more fun, we have the following running scenario:

Carrier Coders has decided to display a Quote of the Day on their website. Each quote is transmitted daily as HEX values. You are tasked with converting the quote to an ASCII string and formatting the output.

💬 Question: How would we write Python code to perform the conversion and randomly display a quote?

We can accomplish this task by one of the following options:


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import codecs
import binascii
import random

Method 1: Use fromhex() and decode()

The fromhex() and decode() functions work well as a one-liner to convert HEX values to an ASCII string. No additional libraries are required for this method.

quote_h = "4368616e67696e67206a6f62732064756520746f20636f2d776f726b6572733f205768793f205468652073616d652070656f706c6520776f726b2074686572652e3b57616c6c79204d6f6f7265"
quote_a = bytes.fromhex(quote_h).decode("ASCII")
quote   = quote_a.replace(';', '\n- ')
print(quote)

The highlighted code takes in HEX values, converts them to a byte object using fromhex(), then converts them to an ASCII string by appending decode() to the end. If quote_a was output to the terminal, the following would display:

Changing jobs due to co-workers? Why? The same people work there.;Wally Moore

To clean up the output, replace() is used on quote_a to replace the semi-colon with a newline and hyphen. The result saves to quote.

Output

Changing jobs due to co-workers? Why? The same people work there.
- Wally Moore

Much better!


Method 2: Use codecs.decode()

This one-liner requires the codecs library for conversion, which contains base classes for encoding and decoding data. Commonly used on Unicode text-based files.

quote_h  = "4d7920736f667477617265206e657665722068617320627567732e204974206a75737420646576656c6f70732072616e646f6d2066656174757265732e3b416e6f6e796d6f7573"
quote_a  = codecs.decode(quote_h, 'hex').decode("ASCII")
quote    = quote_a.replace(';', '\n- ')
print(quote)

The highlighted code takes in HEX values and converts them to a byte object using codecs.decode(), then converts to an ASCII string by appending decode() to the end.

If quote_a was output to the terminal, the following would display:

b'My software never has bugs. It just develops random features.;Anonymous'


To clean up the output, replace() is used on quote_a to replace the semi-colon with a newline and hyphen. The result saves to quote.

Output

My software never has bugs. It just develops random features.
- Anonymous

Method 3: Use join()

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.

quote_h = "4c696665206973206e6f742061626f75742066696e64696e6720796f757273656c662e204c6966652069732061626f7574206372656174696e6720796f757273656c662e3b47656f726765204265726e6172642053686177"
quote   = ''.join([chr(int(''.join(c), 16)) for c in zip(quote_h[0::2],quote_h[1::2])]).replace(';', '\n- ')
print(quote)

The highlighted code takes in a single HEX value and, using zip(), converts the said value to its ASCII equivalent. The characters are then appended to the quote variable to create an entire ASCII string. Finally, replace() is appended to the end to perform the formatting.

Output

Life is not about finding yourself. Life is about creating yourself.
- George Bernard Shaw

Method 4: Use binascii.a2b_hex()

This one-liner calls in the binascii library to convert HEX values to an ASCII string using the binascii.a2b_hex() function.

quote_h = "446f206e6f74207365656b206120706c61636520746f20626c6f6f6d3a20626c6f6f6d20776865726520796f752061726520706c616e7465642e3b57616c6c79204d6f6f7265"
quote = binascii.a2b_hex("%s" % (quote_h.strip())).decode("ASCII").replace(';', '\n- ')
print(quote)

The highlighted code takes in HEX values and converts them to an ASCII equivalent. Finally, replace() is appended to the end to perform the formatting.

Output

Do not seek a place to bloom: bloom where you are planted.
- Wally Moore

Bonus: Generate Random Quote

A more efficient approach to the above would be to place all the quotes in a flat text file. Then randomly select the Daily Quote, convert it, and format it appropriately.

quotes = []

with open('hex-quotes.txt','r') as fp:
    for index, line in enumerate(fp):
        line = bytes.fromhex(line).decode("ASCII").strip()
        quotes.append(line)

num = random.randint(0, len(quotes)-1)
daily = quotes[num].replace(';', '\n- ')
print(daily)

The above code loops through the lines of the quotes file. First, each line is converted from HEX values to its ASCII string equivalent using fromhex() and decode(). Then, the converted string is appended to the quotes list.

A random number is generated and referenced in the quotes list. Finally, the output is formatted and sent to the terminal.

Output

Life is like a box of chocolates, you never know what you are going to get.
- Forrest Gump

Summary

These four (4) methods of converting HEX values to an ASCII string should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!