DEV Community

CarlyRaeJepsenStan
CarlyRaeJepsenStan

Posted on • Updated on

 

Converting Hex to Text - the Bash Way

Let's start by pretending someone gave us some pure plain-text bytes, like this:
68656c6c6f20776f726c64

What are we going to do to find the hidden message?

First, we know that hexadecimal bytes are always 2 characters - you can verify this by using man ascii in your terminal and checking out the tables it shows. Next, we know that you can convert a hex byte into ASCII (or text) by using echo like this:

echo -e "\x61"

# a
Enter fullscreen mode Exit fullscreen mode

What I thought we could do is split the hex string into an array of two-character pieces, and then use a loop to print them like above. So deciphering our hex string is actually pretty straightforwards!

You can use the command fold to first split up the string:

 ~
  ▲ echo $(echo 68656c6c6f20776f726c64 | fold -w2))
68 65 6c 6c 6f 20 77 6f 72 6c 64
Enter fullscreen mode Exit fullscreen mode

And here's a cool fact: by default, anything with spaces is automatically split into a loopable array by bash!

In case you forgot, you use arrays in bash using a rather odd notation: ${arrayname[location]}.

So if we call our previous output spaced:

for i in ${spaced[@]}; 
 do echo -n -e "\x$i";
done
Enter fullscreen mode Exit fullscreen mode

Easy! Thanks for reading my short tutorial, and have a great day. You never know when this might come in useful...

Top comments (2)

Collapse
 
marcomoscatelli profile image
Marco Moscatelli

Great article!

Collapse
 
carlyraejepsenstan profile image
CarlyRaeJepsenStan

Thanks!

50 CLI Tools You Can't Live Without

The top 50 must-have CLI tools, including some scripts to help you automate the installation and updating of these tools on various systems/distros.