Question

I have tried with the following, but it just says "& was unexpected at this time."

@echo off
:enter-input
echo Please enter a number between 1 and 15:
echo 1 = Selection one
echo 2 = Selection two
echo 4 = Selection three
echo 8 = Selection four
echo x = Quit

set INPUT=
set /P INPUT=Type number: %=%

if "%INPUT%" == "" goto enter-input
if "%INPUT%" == "x" goto end
if "%INPUT%" == "X" goto end

set /A %INPUT%
if %INPUT% & 1 == 1 echo Selection one
if %INPUT% & 2 == 2 echo Selection two
if %INPUT% & 4 == 4 echo Selection three
if %INPUT% & 8 == 8 echo Selection four

echo Done
:end
Was it helpful?

Solution 2

I found a way of doing this.

@echo off
:enter-input
echo Please enter a number between 1 and 15:
echo 1 = Selection one
echo 2 = Selection two
echo 4 = Selection three
echo 8 = Selection four
echo x = Quit

set /P INPUT=Type number:

if "%INPUT%" == "" goto enter-input
if "%INPUT%" == "x" goto end
if "%INPUT%" == "X" goto end

set /A isOne = "(%INPUT% & 1) / 1"
set /A isTwo = "(%INPUT% & 2) / 2"
set /A isThree = "(%INPUT% & 4) / 4"
set /A isFour = "(%INPUT% & 8) / 8"

if %isOne% == 1 echo Selection one
if %isTwo% == 1 echo Selection two
if %isThree% == 1 echo Selection three
if %isFour% == 1 echo Selection four

echo Done
:end

OTHER TIPS

It is possible to do the bit-wise math and the comparison all in one statement. The trick is to intentionally create a divide by zero error if the result is what you are looking for. Of course stderr should be redirected to nul, and the || operator is used to test for the error condition (indicating TRUE).

This technique eliminates the need for any intermediate variable.

@echo off
:enter-input
set "input="
echo(
echo Please enter a number between 1 and 15:
echo 1 = Selection one
echo 2 = Selection two
echo 4 = Selection three
echo 8 = Selection four
echo x = Quit

set /P INPUT=Type number:

if not defined input goto enter-input
if /i "%input%" == "X" exit /b

2>nul (
  set /a "1/(1-(input&1))" || echo Selection one
  set /a "1/(2-(input&2))" || echo Selection two
  set /a 1/(4-(input^&4^)^) || echo Selection three
  set /a 1/(8-(input^&8^)^) || echo Selection four
)
pause
goto enter-input

The accepted answer never stated the somewhat obvious: Special characters like & and ) must be either escaped or quoted within the SET /A computation. I intentionally demonstrated both techniques in the example above.


EDIT: The logic can be made even simpler by reversing the logic (divide by zero if false) and using the && operator.

2>nul (
  set /a "1/(input&1)" && echo Selection one
  set /a "1/(input&2)" && echo Selection two
  set /a 1/(input^&4^) && echo Selection three
  set /a 1/(input^&8^) && echo Selection four
)
SET LEFT = 1
SET RIGHT = 2
SET /A RESULT = %LEFT% & %RIGHT%

Please escape the ampersand character (&) with a '^' if you try it directly in cmd.exe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top