bat批处理位运算实例代码

```@echo off
if "%~1" equ "" exit/b
:begin
setlocal enabledelayedexpansion
set "Var=0123456789ABCDEF"
set/p number=Input:
if /i "%number%" equ "cls" cls&endlocal&goto begin
if "%~1" equ ">>" (set "s=!number: ="^>^>"!") else (
if "%~1" equ "<<" (set "s=!number: ="^<^<"!") else (
set "s=!number: ="^%~1^"!"
))
set/a s=!s!
for %%a in (%number% %s%) do (
set/a num=%%a,y+=1
set "bin="
call :loop
if !y! equ 2 (set "str=                  (%~1) %%a") else (set "str=                         %%a")
set "bin=00000000000000000000000000000!bin!"
if !y! equ 3 echo      ------------------------------------------------------
echo  !str:~-15!  ^(bin^) !bin:~-30!
)
endlocal
echo.&goto begin
:loop
set/a Mod=Num%%2,Num/=2
call,set "bin=%%Var:~%Mod%,1%%%bin%"
if %Num% neq 0 goto loop```

&---与，转为2进制，对应位上相乘。

闲扯原码、反码、补码

(-127~-0 +0~127)共256个.

( 1 ) 10- ( 1 )10 = ( 1 )10 + ( -1 )10 = ( 0 )10

(00000001)原 + (10000001)原 = (10000010)原 = ( -2 ) 显然不正确.

( 1 )10 - ( 1 ) 10= ( 1 ) 10+ ( -1 ) 10= ( 0 )10

(00000001) 反+ (11111110)反 = (11111111)反 = ( -0 ) 有问题.

( 1 )10 - ( 2)10 = ( 1 )10 + ( -2 )10 = ( -1 )10

(00000001) 反+ (11111101)反 = (11111110)反 = ( -1 ) 正确

(-128~0~127)共256个.

( 1 ) 10- ( 1 ) 10= ( 1 )10 + ( -1 )10 = ( 0 )10

(00000001)补 + (11111111)补 = (00000000)补 = ( 0 ) 正确

( 1 ) 10- ( 2) 10= ( 1 )10 + ( -2 )10 = ( -1 )10

(00000001) 补+ (11111110) 补= (11111111)补 = ( -1 ) 正确

⑴使符号位能与有效值部分一起参加运算,从而简化运算规则.

⑵使减法运算转换为加法运算,进一步简化计算机中运算器的线路设计