如何从batch file中以hex显示整数?

echo The error level is: %ERRORLEVEL% 

产生

 >The error level is: 15 

我想要什么:

 >The error level is: F 

我需要做转换还是有办法显示不同的数字?

任何帮助正确的方向表示赞赏,谢谢。

只需用vbscript而不是批量编写

把下面的vbscript语句放到一个文件中。

 WScript.Echo Hex( WScript.Arguments(0) ) 

然后运行它,简单地在命令行上键入(在批处理脚本中,如果需要,可以使用for循环捕获值)

 C:\workspace> cscript //nologo hex.vbs 15 F 

没有必要安装任何东西。 在大多数Windows系统中,默认情况下都是vbscript。

很久以前,我很无聊。

cmdcalc.cmd

 @echo off if not defined trace set trace=rem %trace% on SetLocal if "%1"=="/?" ( call :help %0 goto :eof ) Set MinInBase= if /i "%2" EQU "Bin" call :DoBin %1 if /i "%2" EQU "Hex" call :DoHex %1 If not defined BinStr call :DoDec %1 EndLocal & set RET=%RET% goto :eof :DoBin Set MinInBase=2 Set ShiftBy=1 Set StartSyn=0b call :DoCalc %1 goto :eof :DoHex Set MinInBase=16 Set ShiftBy=4 Set StartSyn=0x call :DoCalc %1 goto :eof :DoDec if {%1} EQU {} goto :eof set /a BinStr=%1 set RET=%BinStr% echo %RET% goto :eof :DoCalc Set BinStr= SET /AA=%1 %Trace% %A% :StartSplit SET /AB="A>>%ShiftBy%" %Trace% %B% SET /AC="B<<%ShiftBy%" %Trace% %C% SET /AC=AC %Trace% %C% call :StringIt %C% If %B% LSS %MinInBase% goto :EndSplit set A=%B% goto :StartSplit :EndSplit call :StringIt %B% set RET=%StartSyn%%BinStr% Echo %RET% EndLocal & set RET=%RET% goto :eof :StringIt set Bin=0123456789ABCDEF FOR /F "tokens=*" %%A in ('echo "%%BIN:~%1,1%%"') do set RET=%%A set ret=%ret:"=% Set BinStr=%Ret%%BinStr% goto :eof :help echo %1 syntax: echo. echo %1 Calculation [Hex^|Bin] echo. echo eg %1 12*2 Hex echo. echo gives 0x18. goto :eof 

根据外部资源Windows环境变量 ,有一个未公开的内置只读变量=ExitCode ,它以十六进制格式返回当前的退出代码。 要确保ErrorLevel值等于退出代码,请使用cmd /C exit %ErrorLevel%

所以,如果你使用这个行代码…:

 cmd /C exit %ErrorLevel% echo The error level is: %=ExitCode% 

…你会收到这个(假设ErrorLevel15 ):

 The error level is: 0000000F 

为了摆脱前面的零,使用这个…:

 cmd /C exit %ErrorLevel% for /F "tokens=* delims=0" %%Z in ("=ExitCode%") do set "HEXCODE=%%Z" if not defined HEXCODE set "HEXCODE=0" echo The error level is: %=ExitCode% 

得到这个:

 The error level is: F 
 perl -e"printf qq{The errorlevel is: %X\n}, $ENV{ERRORLEVEL}" 

当然,需要安装Perl ,但这很容易。