How to Print ASCII code from Character on Windows Batch Script?


In previous post, we talk about the method to obtain a character from its ASCII code. In this post, we want the opposite, e.g. to get the ASCII code for given character. For example, ord(A) = 65, ord(0) = 48.

Likewise, the character set supported are from ASCII 32 to 126 however, there are some special characters not supported because they are reserved. These are space (32), !, |, < and >.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@echo off
:: helloacm.com
:: ord function implementation
:: convert character to ASCII
:: does not work for ! < > |
setlocal EnableDelayedExpansion
 
set code=0
if [%1] EQU [] goto END
 
set input=%1
:: get first character of the input
set target=%input:~0,1%
 
    for /L %%i in (32, 1, 126) do (
        cmd /c exit /b %%i
        set Chr=^!=ExitCodeAscii!
        if [^!Chr!] EQU [^!target!] set code=%%i & goto END
    )
goto :EOF
 
:END
    echo !code!
 
:: set return code
endlocal & set errorlevel=%code%
@echo off
:: helloacm.com
:: ord function implementation
:: convert character to ASCII
:: does not work for ! < > |
setlocal EnableDelayedExpansion

set code=0
if [%1] EQU [] goto END

set input=%1
:: get first character of the input
set target=%input:~0,1%

	for /L %%i in (32, 1, 126) do (
		cmd /c exit /b %%i
		set Chr=^!=ExitCodeAscii!
		if [^!Chr!] EQU [^!target!] set code=%%i & goto END
	)
goto :EOF

:END
	echo !code!

:: set return code
endlocal & set errorlevel=%code%

The idea of this method is just to loop (using for /L) between 32 to 126 and check its character expression if it is the same as input. The %=ExitCodeAscii% serves well this purpose. Of course, we need to get the return value by cmd /c exit /b return_code.

To verify the method, we can use command:

for %c in (0,1,2,3,4) do @ord %c

And this should print:

48
49
50
51
52

Please also note that the %errorlevel% is set to the same ASCII value. The setlocal EnableDelayedExpansion is required to delay the string expansion in batch script and we use ! instead of % to retrieve string variables.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
336 words
Last Post: The Chr Function Implementation in Windows Pure Batch Script
Next Post: How to Disable FTP Login Details in WordPress when Upgrading Plugins?

The Permanent URL is: How to Print ASCII code from Character on Windows Batch Script?

Leave a Reply