2

I'd like to convert ASCII code (like -, _, ., etc.) in hexadecimal representation in Unix shell (without bc command). For example, - => %2d.

How can I do it?

2
  • Can sed/awk/perl etc be used? Commented Aug 27, 2010 at 15:37
  • only sed or bash/sh shell please ;) Commented Aug 30, 2010 at 8:23

4 Answers 4

9

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 A
65
$ 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 | xxd
0000000: 00                                       .
$ chr 255 | xxd
0000000: ff                                       .
Sign up to request clarification or add additional context in comments.

1 Comment

thx but ord function gives me decimal value, I'd like the hexadecimal value of the ascii code, thx for your help
1
perl -e 'print ord("_"), "\n"'

1 Comment

thx a lot, I'll use this expression with unpack : perl -e 'print unpack("H*","-"), "\n"'
0

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 .

Comments

0

The following works in the ksh version I'm using:

chr ()
{
    printf \\x$1
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.