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 http://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
2009-12-03

:toHex - convert a decimal number to hexadecimal

Description: call:toHex dec hex
Script:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
:toHex dec hex -- convert a decimal number to hexadecimal
::             -- dec [in]      - decimal number to convert
::             -- hex [out,opt] - variable to store the converted hexadecimal number in
:$created 20091203 :$changed 20091203 :$categories Arithmetic,Encoding
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
set /a dec=%~1
set "hex= "
SET "map=0-0;1-1;2-2;3-3;4-4;5-5;6-6;7-7;8-8;9-9;10-A;11-B;12-C;13-D;14-E;15-F"
for /L %%N in (1,1,8) do (
    set /a d=dec%%16,dec/=16
    call set h=%%map:*!d!-=%%
    set hex=!h:~0,1!!hex!
)
( 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 Ouput
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 Ouput
y = 100