当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何在bat文件中进行按位?》经验,为你挑选了2个好方法。



1> dbenham..:

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



2> loraderon..:

我找到了一种方法.

@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

推荐阅读
ERIK又
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有