Search code examples
windowsbatch-filecmdcharascii

Return character from ASCII code in Windows Batch


I made a program for coding text strings in Batch. Now, I have to convert the ASCII code to a character. In reality, I have to do the opposite. I divided the chars of the strings and I want to translate it to ASCII. I found a good command to convert ASCII to char:

cmd /c exit 65
echo %=exitcodeAscii%

But, when I run it in a for cycle it stops working. With the for iteration I verify if the ASCII code (the for index) is the same of the character.

@echo off
setlocal enableDelayedExpansion
set char=A
for /L %%a in (32,1,126) do (
  cmd /c exit %%a
  echo %=exitcodeAscii%
  if %=exitcodeAscii% EQU %char% echo %%a
)

It seems that the command doesn't work. How can I resolve this?


Solution

  • @echo off
    setlocal enableDelayedExpansion
    set char=A
    for /L %%a in (32,1,126) do (
      cmd /c exit %%a
      echo !=exitcodeAscii!
      if "!=exitcodeAscii!" EQU "%char%" echo %%a
    )
    

    Two little changes:
    a) using delayed expansion (you already enabled it)
    b) qoutes around the if arguments to prevent syntax errror with empty varaibles (especially here the space for %%a = 32, which if can't handle on it's own).