Thursday 31 August 2006

ASCII character conversion

The od command can be used after a fashion to convert from a character to its character code:

 echo -ne "A" | od -t u1 | sed -e "s/^[0-9]* *//"

But more awkward is converting from a decimal character code back to the character, but this does the trick, and took about 3 minutes to come up with:

$ X=65
$ HEX=(0 1 2 3 4 5 6 7 8 9 a b c d e f)
$ echo -e "x${HEX[$(( $X / 16))]}${HEX[$(( $X % 16 ))]}"


It works by converting which is less than 255 to hexadecimal, and then making use of echo -e which interprets \x as indicating an 8 bit character expressed in hexadecimal.

3 comments:

  1. Thanks for the help mate, I am a newbie and was DEAD stuck on converting ASCII ints to chars. May God bless you … ;)

    ReplyDelete
  2. Are you limited to od sed and such?
    The first one can be done as
    echo -ne “A” | perl -ne ‘printf ord $_’
    the second one as
    echo 65 | perl -ne ‘printf “%c”,$_’
    or, if you don’t want to pipe as:
    perl -ne ‘printf ord “A”‘
    perl -ne ‘printf “%c”,65′
    perl is standard on most Unices nowadays

    ReplyDelete
  3. I was limited to not using perl. I guess I could have used awk.

    ReplyDelete