JSI Tip 4367. Using arithmetic, modulus, logical shift, and boolean operators in the SET command.JSI Tip 4367. Using arithmetic, modulus, logical shift, and boolean operators in the SET command.

Jerold Schulman

November 5, 2001

2 Min Read
ITPro Today logo in a gray background | ITPro Today


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% + 28set /a WKYY1=%YY1% / 4set /a WKYY1=%WKYY1% * 4If %WKYY1% NEQ %YY1% goto DAYMset /a DD1=%DD1% + 1

Had I known about the modulus operator, I could have changed this sequence of commands to:

set /a DD1=%DD1% + 28set /a WKYY1=%YY1% ^% 4If %WKYY1% GTR 0 goto DAYMset /a DD1=%DD1% + 1

While 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=1set /a BB=2set /a CC=3set /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=8set /a bb="aa << 1"

shifts the bits in %aa% left by 1, which multiplies by 2, whereas:

set /a aa=8set /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 or

Thus:

set /a byte=0x01set /a xx="byte & 0xFF" leaves the 0 bit onset /a xx="byte & 0xFE" turns the 0 bit offset /a xx="byte ^ 0xFF" reverses the the 0/1 condition of the bits. set /a xx="byte | 0xFF" turns all bits on



Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like