¿Cómo hago un bit a bit y en un archivo bat?
-
22-07-2019 - |
Pregunta
He intentado con lo siguiente, pero solo dice & amp; & amp; fue inesperado en este momento. "
@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
Solución 2
Encontré una forma de hacerlo.
@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
Otros consejos
Es posible hacer las matemáticas y la comparación todo en una sola declaración. El truco es crear intencionalmente un error de división por cero si el resultado es lo que está buscando. Por supuesto, stderr debe ser redirigido a nul, y el operador ||
se usa para probar la condición de error (indicando VERDADERO).
Esta técnica elimina la necesidad de cualquier variable intermedia.
@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
La respuesta aceptada nunca dijo algo obvio: los caracteres especiales como & amp;
y )
deben escaparse o citarse dentro del cómputo SET / A. Demostré intencionalmente ambas técnicas en el ejemplo anterior.
EDITAR: La lógica se puede simplificar aún más invirtiendo la lógica (dividir por cero si es falso) y utilizando el operador & amp; & amp;
.
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
)
SET LEFT = 1
SET RIGHT = 2
SET /A RESULT = %LEFT% & %RIGHT%
Por favor, escapa del carácter de signo (& amp;) con un '^' si lo intentas directamente en cmd.exe.