Re: [missing the obvious?] ascii->int

From: Chris F.A. Johnson (cfajohnson_at_gmail.com)
Date: 07/29/05


Date: Fri, 29 Jul 2005 16:38:36 -0400


[follow-up set to comp.unix.shell]

On 2005-07-29, giacomo boffi wrote:
> ok, i'm probably missing the obvious, but i'd like to write a program
> to convert ascii to integer:
> ,----
>| % echo A | awk -f ascii2int
>| 65
>| %
> `----
>
> and i cannot figure out the appropriate trick...

    Unless there's a particular reason to use awk, I'd use the shell:

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

> ps: oh, what i really need is a "aseq" program:
> ,----
>| % echo e | awk -f aseq
>| a
>| b
>| c
>| d
>| e
>| % echo D | awk -f aseq
>| A
>| B
>| C
>| D
>| %
> `----
>
> but i think that's in my reach, if i know how to do step 1 ;

    Again, the shell is easy enough (and you do not need step 1):

aseq() {
  alpha='A B C D E F G H I J K L M N O P Q R S T U V W X Y Z'
  printf "%s\n" ${alpha%$1*} $1
}

    Even easier in bash3:

aseq() {
  eval "printf '%s\n' {A..$1}"
}

-- 
    Chris F.A. Johnson                     <http://cfaj.freeshell.org>
    ==================================================================
    Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress
    <http://www.torfree.net/~chris/books/cfaj/ssr.html>


Relevant Pages