Anchor(faq71)

How do I convert an ASCII character to its decimal (or hexadecimal) value and back?

This task is quite easy while using the printf builtin. You can either write two simple functions as shown below or use the plain printf constructions alone.

   # chr() - converts decimal value to its ASCII character representation
   # ord() - converts ASCII character to its decimal value
 
   chr() {
     printf \\$(printf '%03o' $1)
   }
 
   ord() {
     printf '%d' "'$1"
   }

   hex() { 
      printf '%x' "'$1"
   }

   # examples:
 
   chr $(ord A)    # -> A
   ord $(chr 65)   # -> 65

The ord function above is quite tricky. It can be re-written in several other ways (use that one that will best suite your coding style or your actual needs).

   ord() {
     printf '%d' \"$1\"
   }

Or:

   ord() {
     printf '%d' \'$1\'
   }

Or, rather:

   ord() {
     printf '%d' "'$1'"
   }

Etc. All of the above ord functions should work properly. Which one you choose highly depends on particular situation.

There is also an alternative when printing characters by their ascii value that is using escape sequences like:

   echo $'\x27'

which prints a literal ' (there 27 is the hexadecimal ascii value of the character).