Script Recipe: How to evaluate numerical expressions in the command line

Here is a little known feature of our beloved CMD.EXE. It is extremely easy to evaluate an arithmetic expression! All it takes is a five characters. Just type set /a followed by your expression.

Here is an example:

E:\>set /a 1+1

Or, if you want, you can convert hex numbers to decimal:

E:\>set /a 0x8000ffff

Or even more, you can use and assign variables:

E:\>set /a i=1+2
E:\>set /a j=i+1

You can use this everywhere, for example in loops:

E:\>for /L %i in (1,1,10) do @set /a 1^<^<%i & echo.

So what operators can you use? That’s easy to figure out. Here is a snippet from the “set /?” help text…

The /A switch specifies that the string to the right of the equal sign
is a numerical expression that is evaluated.  The expression evaluator
is pretty simple and supports the following operations, in decreasing
order of precedence:

    ()                  – grouping
    ! ~ –               – unary operators
    * / %               – arithmetic operators
    + –                 – arithmetic operators
    << >>               – logical shift
    &                   – bitwise and
    ^                   – bitwise exclusive or
    |                   – bitwise or
    = *= /= %= += -=    – assignment
      &= ^= |= <<= >>=
    ,                   – expression separator

If you use any of the logical or modulus operators, you will need to
enclose the expression string in quotes.  Any non-numeric strings in the
expression are treated as environment variable names whose values are
converted to numbers before using them.  If an environment variable name
is specified but is not defined in the current environment, then a value
of zero is used.  This allows you to do arithmetic with environment
variable values without having to type all those % signs to get their
values.  If SET /A is executed from the command line outside of a
command script, then it displays the final value of the expression.  The
assignment operator requires an environment variable name to the left of
the assignment operator.  Numeric values are decimal numbers, unless
prefixed by 0x for hexadecimal numbers, and 0 for octal numbers.
So 0x12 is the same as 18 is the same as 022. Please note that the octal
notation can be confusing: 08 and 09 are not valid numbers because 8 and
9 are not valid octal digits.

Comments (2)

  1. Raghu says:

    Hmmmmm….O M G!!!!!!!