1) Added support for negative numbers (the wonders of two's complement math)
2) Eliminated leading zeros from output (personal preference)
3) The new Hex map lookup strategy is simpler and slightly faster
Code: Select all
:toHex dec hex -- convert a decimal number to hexadecimal
:: -- dec [in] - decimal number to convert
:: -- hex [out,opt] - variable to store the converted hexadecimal number in
setlocal enabledelayedexpansion
set /a dec=%~1
if %dec% lss 0 (set neg=*-1-1) else if defined neg set neg=
set /a dec=dec%neg%
if defined hex set hex=
set "map=0123456789ABCDEF"
for /l %%n in (1,1,8) do (
if not !dec!%neg%==0 (
set /a d=dec%%16%neg%,dec/=16
for /l %%d in (!d!,1,!d!) do set "hex=!map:~%%d,1!!hex!"
)
)
if not defined hex set hex=0
(endlocal & rem return values
if "%~2" neq "" (set %~2=%hex%) else echo:%hex%
)
exit /b
A simple way to test the function is to call :toHex with a number in hex format as in
call :toHex 0xFFFFFFFF
The output should always match the input.
Dave Benham