Explain Codes LogoExplain Codes Logo

Convert from ASCII string encoded in Hex to plain ASCII?

python
hex-to-ascii
character-encoding
python-stdlib
Alex KataevbyAlex Kataev·Nov 29, 2024
TLDR

To transform a hex string to ASCII:

ascii_str = bytes.fromhex("68656c6c6f").decode() # hex to 'hello'

Just use bytes.fromhex() and then .decode() on the hex string. Works like a charm.

Understanding character encoding

At the root of it, ASCII and Unicode represent characters as numerical codes. In hexadecimal notation, an ASCII character corresponds to a byte, or two hex digits, like 68 for h.

Methods for Hex to ASCII conversion

Use the binascii module

When bytes.fromhex() feels too mainstream, there's always binascii.unhexlify():

import binascii ascii_str = binascii.unhexlify("68656c6c6f").decode('ascii') # hex to 'hello'

Convert hex to integer manually

If you like living life in the fast lane and doing things manually, parse hex values and convert to ASCII characters:

ascii_str = ''.join(chr(int(''.join(pair), 16)) for pair in zip(*[iter("68656c6c6f")] * 2)) # 'cause who needs libraries, right?

Decoding non-ASCII encodings

Sometimes, you stumble upon non-ASCII characters (they just like to stand out). Here’s how you handle them gracefully:

non_ascii = bytes.fromhex("e38182e38184e38186").decode('utf-8') # hex to Japanese 'あいう', brings out your multilingual flair

Explicit UTF-8 decoding respects multibyte characters.

Avoiding common pitfalls

Clean your hex input

Before anything, make sure your hex string is just hex, no spaces, no 0x - just pure unadulterated hexadecimal:

clean_hex = "68656C6C6F".replace(' ', '').lower().lstrip('0x') # hex cleanup, because cleanliness is next to godliness ascii_str = bytes.fromhex(clean_hex).decode('ascii')

Python 2 method is deprecated

Once upon a time, in Python 2, .decode('hex') was the go-to method, but now it's time to move on and embrace Python 3.

Advanced hex conversions

  • Why stop here? Let's explore the possibilities:

Functional programming style?

If you're into functional programming, this one's for you:

from functools import partial hex_to_int = partial(int, base=16) # you'll hex to the power of int ascii_str = ''.join(map(chr, map(hex_to_int, ("68", "65", "6c", "6c", "6f")))) # because map() is the key to happiness

No external libraries needed

Python's standard library is a treasure trove. You don't always need to venture out into the ocean of external libraries.

Readability over complexity

Above all, comprehensible code is key. Choose a method that makes your code readable and maintainable.