windows - 如何在 bat 文件中按位制作?

标签 windows batch-file cmd 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

最佳答案

可以在一个语句中进行按位数学运算和比较。诀窍是如果结果是您正在寻找的结果,则有意地创建除以零错误。当然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 计算中转义或引用。我有意在上面的示例中演示了这两种技术。

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

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

相关文章:

windows - 用于在子文件夹中查找文件夹并获取路径的批处理脚本

batch-file - 如何更改 IF 语句中的当前目录并使用环境变量 CD 引用其路径?

windows - Windows 控制台对 Unicode 有什么限制?

c++ - 如何在visual studio 2008中进行调试

c++ - 使 Stack Walker 在启用优化的应用程序中工作

batch-file - 在 TeamCity 9 的一个构建步骤中运行两个批处理文件

c - 为什么 system() 函数不起作用?

c# - 托盘中更好的通知

c# - 上传到 Azure Block Blob 时如何选择最佳 block 大小

regex - 如何使用 Windows 命令行工具或批处理文件从日志文件中提取行?