Batchography: Converting numbers to characters (or the CHR() function)

In various programming languages, you might sometimes need to convert numbers to characters. In simple terms, each character you see has a numerical representation. The ASCII table  shows the numbers of each character and its corresponding glyph.

Converting numbers to their corresponding characters would be useful to generate a random string for instance. The first step to generating a random string is to generate random numbers between 65 and 90 (upper case ‘A’ to upper case ‘Z’) or between 97 and 122 (lower case ‘a’ to lower case ‘z’).

While the Batch language is pretty primitive, you would be surprised how many things you can do with it. In the Batchography book, I cover various topics that would bring your Batch programming skills to the next level.
batchography-good-res

Get the book from Amazon:

  • Paperback editionbtn-buy-on-amazon
  • E-book editionbtn-buy-on-amazon

flower separator

The following code snippets illustrates how to write the Ordinal to Character conversion function:

:ord2chr <1=ordinal value> => %result%
  for %%a in ("65=A" "66=B" "67=C" "68=D"
      "69=E" "70=F" "71=G" "72=H" 
      "73=I" "74=J" "75=K" "76=L" 
      "77=M" "78=N" "79=O" "80=P" 
      "81=Q" "82=R" "83=S" "84=T" 
      "85=U" "86=V" "87=W" "88=X" 
      "89=Y" "90=Z" "97=a" "98=b" 
      "99=c" "100=d" "101=e" "102=f" 
      "103=g" "104=h" "105=i" "106=j" 
      "107=k" "108=l" "109=m" "110=n" 
      "111=o" "112=p" "113=q" "114=r" 
      "115=s" "116=t" "117=u" "118=v" 
      "119=w" "120=x" "121=y" "122=z" 
      "48=0" "49=1" "50=2" "51=3"
      "52=4" "53=5" "54=6" "55=7" 
           "56=8" "57=9") do (
  for /f "usebackq tokens=1-2 delims==" %%b in ('%%~a') do (
      if "%1"=="%%b" (
        set result=%%c
        goto :eof
      )
    )
  )

As you can see from the above, the Batch function takes one input argument which is the number to convert to a character. The result is returned into the result environment variable. The function employs a mapping table that will be used to convert the numbers to their corresponding characters.

The ord2chr function can be used to generate a random string. Consider the following function:

:gen-rand-str <1=length> <2=mod> <3=base> => %result%
  set str=
  for /l %%a in (1, 1, %1) do (
    set /A N="(!RANDOM! %% %2) + %3"
    call :ord2chr !N!
    set str=!str!!result!
  )
  set result=%str%

  goto :eof

The gen-rand-str function employs the ord2chr and the RANDOM pseudo-environment variable in order to generate a random string.

Please refer to Chapter 4 in the Batchography book for a more detailed explanation on the topic and other advanced Batch scripting topics.
flower separatorYou might also like:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.