Link to home
Start Free TrialLog in
Avatar of myrizvi
myrizvi

asked on

Char to hex and hex to char in shell

Hi experts,

The following printf command converts a char to a hex value:

$ printf "%x" a
61

How can I conver this 61 back to "a" by using printf or any shell command?

Thanks

Avatar of ahoffmann
ahoffmann
Flag of Germany image

which shell are you using?
Avatar of myrizvi
myrizvi

ASKER

Hi ahoffman,

I am using ksh.
printf '\x61'

Though I don't understand how `printf "%x" a` produces the hex value of "a"  :-(
Avatar of myrizvi

ASKER

$ printf '\x61'
x61

The above command is not producing desired result.

printf just converted the "a" to its hex value when used with "%x" option.

 
please post version of OS, version of ksh, and result of
  which printf
ASKER CERTIFIED SOLUTION
Avatar of tfewster
tfewster
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Tintin
Now there's obviously some interesting differences in printf versions and whether it's using a builtin like ksh/bash or the printf binary.

On Solaris 9 at least the bash and ksh builtin versions of printf give the same results as /usr/bin/printf

tfewster, what OS/shell are you using that produces 'a' with

printf "%x" a

On Solaris 9, I get

printf: a expected numeric value

myrizvi.

I've tried

printf '\x61'

on Solaris under ksh/bash and the printf binary.  I've tried under FreeBSD and Redhat Linux, and the printf builtins work and on Redhat the /usr/bin/printf works, but on FreeBSD /usr/bin/printf produces

x61

Are you using FreeBSD or similar?

>  Now there's obviously some interesting differences in ..
.. HP-UX
I guess it's worth looking in /usr/dt/bin where HP-UX stores the well known working standard executables ;-)
Curioser and curioser...It's not working for me on Solaris and printf doesn't appear to be built in to ksh on either HP-UX or Solaris...
(See my previous post for HP version details)

# uname -a
SunOS SUNMCC 5.9 Generic_112233-11 sun4u sparc SUNW,Sun-Blade-1000
# printf '\x61'
\x61
# which printf
/usr/bin/printf
export PATH=""
# printf '\x61'
ksh: printf:  not found
# echo $SHELL
/bin/ksh





I was wrong in my initial statement.  On Solaris only bash printf works as it is a shell builtin.  ksh doesn't have a printf builtin and the printf binary gives the undesired result.

# uname -sr
SunOS 5.9
# echo $0
bash
# type printf
printf is a shell builtin
# printf '\x61'
a# /usr/bin/printf '\x61'
\x61# exec ksh
# type printf
printf is /usr/bin/printf
Avatar of myrizvi

ASKER

Thanks to all of you.

Right tfewster's solution is working for me, so I will accept this answer.

The unix is HP-UX 11.11 and ksh is /bin/ksh.