如何在bat文件中进行按位?

时间:2009-01-13 14:02:15

标签: batch-file dos bit-manipulation

我尝试了以下内容,但它只是说“此时出现意外情况。”

@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 个答案:

答案 0 :(得分:8)

可以在一个语句中进行逐位数学运算和比较。诀窍是如果结果是您正在寻找的,故意创建除零错误。当然应该将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
)

答案 1 :(得分:5)

我找到了一种方法。

@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

答案 2 :(得分:1)

对于按位AND,请将表达式放在引号中以避免错误
例如。 set /a "48 & 23"

答案 3 :(得分:0)

SET LEFT = 1
SET RIGHT = 2
SET /A RESULT = %LEFT% & %RIGHT%

如果直接在cmd.exe中试用,请使用'^'转义符号字符(&)。