When using the Windows set /p and set /a commands to accept a开发者_如何学C hexadecimal value from the command line and convert it to decimal. What I need is to be able to take a decimal value and set and environment variable with its hexadecimal equivalent.
Current batch file coding:
@echo off
set HexV1=%1
set HexV2=%2
set /A DecV1=0x%HexV1%
set /A DecV2=0x%HexV2%
set /A HexV3=0x%HexV1% + 0x1
set /A HexV4=0x%Hexv2% + 0x2
set Dec
set Hex
Produces:
C:>hexmath a f
DecV1=10
DecV2=15
HexV1=a
HexV2=f
HexV3=11
HexV4=17
What I need is to be able to set HexV3
to b and HexV4
to 11.
Any suggestions?
The batch file on channel9 was much to long for my tastes. Here's a simpler (IMO) version of "tohex.bat" that I just whipped up:
@echo off & setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
set LOOKUP=0123456789abcdef &set HEXSTR=&set PREFIX=
if "%1"=="" echo 0&goto :EOF
set /a A=%*
if !A! LSS 0 set /a A=0xfffffff + !A! + 1 & set PREFIX=f
:loop
set /a B=!A! %% 16 & set /a A=!A! / 16
set HEXSTR=!LOOKUP:~%B%,1!%HEXSTR%
if %A% GTR 0 goto :loop
echo %PREFIX%%HEXSTR%
It works in much the same way as the other script (iteratively dividing by 16), but it uses a string lookup (instead of a series of "if" statements) to build the hex string. It handles negative numbers as well (two's complement), but it's a bit of a hack.
You could call it from your other batch file like so:
for /f "delims=" %%Q IN ('call tohex.bat 0x%HexV1% + 0x1') DO SET HexV3=%%Q
Hope that helps.
There is an extremely fast and efficient solution at http://www.dostips.com/DtCodeCmdLib.php#toHex. Like the selected answer, it uses a hex map and supports negative numbers. It uses some very clever bit manipulation, and does all looping with a FOR /L statement.
The selected answer is comparatively slow because it relies on a GOTO loop.
This forum post at channel9.msdn.com has a batch script that will convert from integer to hex.
If has a loop using a GOTO
and processes the number using the modulo - SET /A
& %
- and integer division - SET /A
& /
- operators and some IF
statements to build up the hex string.
I just found a great solution from Voodooman at http://www.dostips.com/forum/viewtopic.php?t=2261. It only works up to 32 bit tho :-( Here's my wrapper script, DecToHex.bat
CALL CMD.EXE /C EXIT /B %~1
SET HEXVAL=%=EXITCODE%
SET "%~2=%HEXVAL%"
EXIT /B 0
Call it like:
>DecToHex.bat 123456 HEXVAL
>ECHO %HEXVAL%
0001E240
精彩评论