You can mask the bits in the random value (And
operation = &
operator) to retrieve the lower two, getting a number in the range [0,3] and adding 1 to adapt to the indicated range
set /a "num=(%random% & 3) + 1"
Or, as the random value generated uses 15 bits, it can be shifted to retrieve only the two upper bits
set /a "num=(%random% >> 13) + 1"
The parenthesis are needed in both cases because +
operator has higher precedence than &
or >>
operators.
You can also use a Mod
operation (%
operator) to retrieve the remainder from a division by 4, also getting a number in the range [0,3]
set /a "num=%random% %% 4 + 1"
The %
operator (inside batch files the %
has to be escaped so it becomes %%
) has higher precedence than the +
operator, so here parenthesis are not needed.