Convert ASCII code to hexadecimal in a Unix shell script Convert ASCII code to hexadecimal in a Unix shell script unix unix

Convert ASCII code to hexadecimal in a Unix shell script


This works in Bash, Dash (sh), ksh, zsh and ash and uses only builtins:

Edit:

Here is a version of ord that outputs in hex and chr that accepts hex input:

ordhex (){    printf '%x' "'$1"}chrhex (){    printf \\x"$1"}

The original decimal versions:

ord (){    echo -n $(( ( 256 + $(printf '%d' "'$1"))%256 ))}

Examples (with added newlines):

$ ord ' '32$ ord _95$ ord A65$ ord '*'42$ ord \~126

Here is the corresponding chr:

chr (){    printf \\$(($1/64*100+$1%64/8*10+$1%8))}

Examples:

$ chr 125}$ chr 42*$ chr 0 | xxd0000000: 00                                       .$ chr 255 | xxd0000000: ff                                       .


perl -e 'print ord("_"), "\n"'


python -c 'import sys; print "{0:02x}".format(ord(sys.argv[1]))' '_'

or

python -c 'print "{0:02x}".format(ord("_"))'

I agree that it's not the nicest one-liner, but I couldn't resist after seeing the Perl based answer .