Batch scripts can do simple 32-bit integer arithmetic and bitwise manipulation using SET /a command. The largest supported integer is 2147483647 = 2 ^ 31 - 1. The smallest supported integer is -2147483648 = - (2 ^ 31), assignable with the trick of set /a num=-2147483647-1
. The syntax is reminiscent of the C language.
Arithmetic operators include *, /, % (modulo), +, -. In a batch, modulo has to be entered as "%%".
Bitwise operators interpret the number as a sequence of 32 binary digits. These are ~ (complement), & (and), | (or), ^ (xor), << (left shift), >> (right shift).
A logical operator of negation is !: it turns zero into one and non-zero into zero.
A combination operator is ,: it allows more calculations in one set command.
Combined assignment operators are modeled on "+=", which, in "a+=b", means "a=a+b". Thus, "a-=b" means "a=a-b". Similarly for *=, /=, %=, &=, ^=, |=, <<=, and >>=.
The precedence order of supported operators, is as follows:
( )
* / % + -
<< >>
&
^
|
= *= /= %= += -= &= ^= |= <<= >>=
,
Literals can be entered as decimal (1234), hexadecimal (0xffff, leading 0x), and octal (0777, leading 0).
The internal bit representation of negative numbers is two's complement. This provides a connection between arithmetic operations and bit operations. For instance, -2147483648 is represented as 0x80000000, and therefore set /a num=~(-2147483647-1) yields 2147483647, which equals 0x7FFFFFFF (type set /a num=0x7FFFFFFF to check).
As some of the operators have special meaning for the command interpreter, an expression using them needs to be enclosed in quotation marks, such as this:
set /a num="255^127"
set /a "num=255^127"