Tuesday, September 11, 2012

Batch files do arithmetic

http://ss64.com/nt/set.html


It's the SET command with a /A parameter.  Sorry for not knowing this sooner.
You can use SET /? to get generic details, or see the SS64's examples below.
Check out SET /P as well to prompt for a variable.

The expression to be evaluated can include the following operators:
   +   Add                set /a "_num=_num+5"
   +=  Add variable       set /a "_num+=5"
   -   Subtract (or unary)set /a "_num=_num-5"
   -=  Subtract variable  set /a "_num-=5"
   *   Multiply           set /a "_num=_num*5"
   *=  Multiply variable  set /a "_num*=5"
   /   Divide             set /a "_num=_num/5"
   /=  Divide variable    set /a "_num/=5"
   %   Modulus            set /a "_num=5%%2"
   %%= Modulus            set /a "_num%%=5" 
   !   Logical negation  0 (FALSE) ⇨ 1 (TRUE) and any non-zero value (TRUE) ⇨ 0 (FALSE)
   ~   One's complement (bitwise negation) 
   &   AND                set /a "_num=5&3"    0101 AND 0011 = 0001 (decimal 1)
   &=  AND variable       set /a "_num&=3"
   |   OR                 set /a "_num=5|3"    0101 OR 0011 = 0111 (decimal 7)
   |=  OR variable        set /a "_num|=3"
   ^   XOR                set /a "_num=5^3"    0101 XOR 0011 = 0110 (decimal 6)
   ^=  XOR variable       set /a "_num=^3"
   <<  Left Shift.    (sign bit ⇨ 0)
   >>  Right Shift.   (Fills in the sign bit such that a negative number always remains negative.)
                       Neither ShiftRight nor ShiftLeft will detect overflow.
   <<= Left Shift variable     set /a "_num<<=2"
   >>= Right Shift variable    set /a "_num>>=2"

  ( )  Parenthesis group expressions  set /a "_num=(2+3)*5"
   ,   Commas separate expressions    set /a "_num=2,_result=_num*5"

If a variable name is specified as part of the expression, but is not defined in the
current environment, then SET /a will use a value of 0.