LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   [bash] ASCII to HEX and hex to ascii (https://www.linuxquestions.org/questions/programming-9/%5Bbash%5D-ascii-to-hex-and-hex-to-ascii-488357/)

es131245 03-20-2014 01:23 PM

awk -version
awk version 20121220 (FreeBSD)

strange. System is updated. So its a third side soft

mattthumper 05-11-2016 07:29 AM

SPF - Thanks!
 
Quote:

Originally Posted by SPF (Post 4950137)
What if your string is:
48656C6C6F2074686572652021

And you don't have perl, python, xxd or uni2ascii?
And you are not allowed to install it.

How can you convert it?

Or course I could always write a loop and read it in pairs:

Code:

#!/bin/bash
function hex2string () {
  I=0
  while [ $I -lt ${#1} ];
  do
    echo -en "\x"${1:$I:2}
    let "I += 2"
  done
}
hex2string "48656C6C6F2074686572652021"


SPF, almost 3 years to the day later, your reply/post is just what I needed!
Thanks, Matt

thedonco 05-08-2018 09:55 PM

I was trying to easily convert back and forth between C-syntax Hex and Ascii (used a lot in Arduino, because apparently that's a fun way to store web pages on embedded controllers), and stumbled upon this thread. It was useful to completing my task, so thought it worth giving back. If nothing else, when I need to do this for something else and misplace these little utils, perhaps my web search will bring me here. :p

The following scriptlettes should be rather light weight and only use fairly standard POSIX utils (od, sed, bash).

$ cat asc2hex
Code:

#!/bin/bash

while read line; do
        echo $line|od -An -tx1|sed 's/ /, 0x/g;s/^, //;s/$/,/'
done < "${1:-/dev/stdin}"

exit 0

$ cat hex2asc
Code:

#!/bin/bash

while read line; do
        echo -en `echo $line|sed 's/, 0x/\\\\x/g;s/^0x/\\\\x/;s/,$//'`
done < "${1:-/dev/stdin}"

exit 0

Example usage:
Code:

$ echo "Hello World!"|./asc2hex
0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21, 0x0a,

$ echo "Hello World!"|./asc2hex|./hex2asc
Hello World!

Alternatively, scriptlettes will also accept direct file as an option:
Code:

$ cat hello_world
Hello World!

$ ./asc2hex hello_world
0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21, 0x0a,

$ ./asc2hex hello_world|./hex2asc
Hello World!



All times are GMT -5. The time now is 03:22 AM.