我已经尝试了以下内容,但它只是说“&此时出乎意料”。

@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

最佳答案

可以在一个语句中进行按位计算和比较。诀窍是如果结果是您正在寻找的结果,则有意地创建除以零错误。当然stderr应该重定向到nul,使用||操作符来测试错误条件(表示TRUE)。

这种技术消除了对任何中间变量的需要。

@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

接受的答案从未说明过一些明显的问题:像 &) 这样的特殊字符必须在 SET/A 计算中转义或引用。我有意在上面的示例中演示了这两种技术。

编辑: 通过反转逻辑(如果为假则除以零)并使用 && 运算符,可以使逻辑更加简单。
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
)

关于windows - 如何在 bat 文件中按位制作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/439038/

10-11 15:57