The arithmetic variant of the SET command, SET /A, can also calculate a modulus, perform logical bit shifts, and do boolean operations.
I first used the arithmetic operations in tip 0721 » General purpose date math routine.
I used the following commands to calculate whether the current year was a leap year, so I could make February have 29 days:
set /a DD1=%DD1% + 28 set /a WKYY1=%YY1% / 4 set /a WKYY1=%WKYY1% * 4 If %WKYY1% NEQ %YY1% goto DAYM set /a DD1=%DD1% + 1Had I known about the modulus operator, I could have changed this sequence of commands to:
set /a DD1=%DD1% + 28 set /a WKYY1=%YY1% ^% 4 If %WKYY1% GTR 0 goto DAYM set /a DD1=%DD1% + 1While this only saves 1 statement, it does save considerable processor time.
When using the SET /A command, you can enclose the string to the right of the = sign in double-quotes ("), causing the expression evaluator to consider any non-numeric strings in the expression as environment variable names, whose values are converted to numbers before using them. This eliminates the need to type all the % signs. Thus set /a WKYY1=%YY1% ^% 4 becomes set /a WKYY1="YY1 % 4"
Consider the following:
set /a AA=1 set /a BB=2 set /a CC=3 set /a quot=(%AA% + %BB%) / %CC% The last line can be typed as: set /a quot="(AA + BB) / CC"You can use the logical shift to shift bits left or right, thus multiplying or dividing by 2:
set /a aa=8 set /a bb="aa << 1"shifts the bits in %aa% left by 1, which multiplies by 2, whereas:
set /a aa=8 set /a bb="aa << 2"shifts the bits in %aa% left by 2, which multiplies by 4. Similarly:
set /a bb="aa >> 2"
shifts the bits in %aa% right by 2 bits, dividing by 4.
Boolean operations are performed by using:
& - bitwise and ^ - bitwise exclusive or | - bitwise orThus:
set /a byte=0x01 set /a xx="byte & 0xFF" leaves the 0 bit on set /a xx="byte & 0xFE" turns the 0 bit off set /a xx="byte ^ 0xFF" reverses the the 0/1 condition of the bits. set /a xx="byte | 0xFF" turns all bits on