DOS - Arithmetic

How to use SET /A for arithmetic in DOS



TOP
2009-12-03

:toDec - convert a hexadecimal number to decimal

Description: call:toDec hex dec
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
:toDec hex dec -- convert a hexadecimal number to decimal
::             -- hex [in]      - hexadecimal number to convert
::             -- dec [out,opt] - variable to store the converted decimal number in
:$created 20091203 :$changed 20091203 :$categories Arithmetic,Encoding
:$source https://www.dostips.com
SETLOCAL
set /a dec=0x%~1
( ENDLOCAL & REM RETURN VALUES
    IF "%~2" NEQ "" (SET %~2=%dec%) ELSE ECHO.%dec%
)
EXIT /b

TOP
2011-03-30

:toHex - convert a decimal number to hexadecimal, i.e. -20 to FFFFFFEC or 26 to 0000001A

Description: call:toHex dec hex
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
:toHex dec hex -- convert a decimal number to hexadecimal, i.e. -20 to FFFFFFEC or 26 to 0000001A
::             -- dec [in]      - decimal number to convert
::             -- hex [out,opt] - variable to store the converted hexadecimal number in
::Thanks to 'dbenham' dostips forum users who inspired to improve this function
:$created 20091203 :$changed 20110330 :$categories Arithmetic,Encoding
:$source https://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
set /a dec=%~1
set "hex="
set "map=0123456789ABCDEF"
for /L %%N in (1,1,8) do (
    set /a "d=dec&15,dec>>=4"
    for %%D in (!d!) do set "hex=!map:~%%D,1!!hex!"
)
rem !!!! REMOVE LEADING ZEROS by activating the next line, e.g. will return 1A instead of 0000001A
rem for /f "tokens=* delims=0" %%A in ("%hex%") do set "hex=%%A"&if not defined hex set "hex=0"
( ENDLOCAL & REM RETURN VALUES
    IF "%~2" NEQ "" (SET %~2=%hex%) ELSE ECHO.%hex%
)
EXIT /b

TOP
2008-04-01

Floating Point Arithmetic - Working around the limitations of the command processor

Description: Floating point arithmetic can be achieved by moving the fractions into the integer. I.e. A floating point equitation using values with 3 digits after the dot can be calculated as follows:
Floating Point: 12.055 + 1.001 = 13.056
Integer:        12055 + 1001 = 13056
Script:
1.
2.
set /a y=12055 + 1001
echo.y = %y%
Script Output:
 DOS Script Output
y = 13056

TOP
2008-04-01

Large Integers - Working around the limitations of the command processor


TOP
2008-04-01

Percent - Basic Percent arithmetic


TOP
2008-04-01

SET /A - Basic Integer Arithmetic

Description: The SET /A command can be used for basic arithmetic.
You can write SET /a y=3*x or SET /a y=3*%x%. Both are correct. The command interpreter is smart enough to recognize variables within a formula.
Script:
1.
2.
3.
4.
5.
set /a x=20
set /a y=3*x
set /a y+=140
set /a y/=2
echo.y = %y%
Script Output:
 DOS Script Output
y = 100


Ad: