How to make bitwise and in bat file?

I 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 
+4
source share
3 answers

I found a way to do 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 
+5
source

You can do bit math and compare everything in one statement. The trick is to deliberately create a division by zero error if the result is what you are looking for. Of course stderr should be redirected to nul, and the operator || used to check for error conditions (indicating TRUE).

This method 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 was never said to be somewhat obvious: special characters such as & and ) must either be escaped or specified in the SET / A calculation. I deliberately demonstrated both techniques in the above example.


EDIT:. The logic can be made even simpler by changing 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 ) 
+7
source
 SET LEFT = 1 SET RIGHT = 2 SET /A RESULT = %LEFT% & %RIGHT% 

Please avoid the ampersand (&) character with "^" if you try it directly in cmd.exe.

0
source

All Articles