The set /A
command does not feature comparison operators.
However, there is a way to compare two numbers and to get a value of -1
if the first number is less than the second one. For this, we need to know that the logical right-shift operator >>
actually performs an arithmetic shift, meaning that the value of the most significant bit, which represents the sign, is shifted in at the left, hence the current sign of the number is maintained.
So for example:
- the number
+10
(binary representation 00000000 00000000 00000000 00001010
) shifted to the right by one bit becomes +5
(binary representation 00000000 00000000 00000000 00000101
);
- the number
-10
(binary representation 11111111 11111111 11111111 11110110
) shifted to the right by one bit becomes -5
(binary representation 11111111 11111111 11111111 11111011
);
When we shift to the right by 31 (or more) bit positions, the result is 32 times the sign bit (as we have 32-bit signed integers), which results in a value of -1
for negative input values and 0
for others.
When we now apply this technique, it leads us to the following code:
set /A "number1=%number1%-((%number1%-%number2%)>>31)"
You may omit the surrounding %
-signs since set /A
interprets any character strings that do not represent numbers or operators as variable names anyway:
set /A "number1=number1-((number1-number2)>>31)"
This can be further simplified using the appropriate assignment operator:
set /A "number1-=(number1-number2)>>31"