Page 1 of 1

Enhanced toHex function

Posted: 27 Mar 2011 22:57
by dbenham
This proposed replacement for toHex has the following improvements:

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

Re: Enhanced toHex function

Posted: 30 Mar 2011 20:43
by DosItHelp
dbenham,

Very good!
Inspired by your post the :toHex function has been made more efficient and now handles negative numbers. I preferred the leading zeros option and so the new implementation is a bit different than you suggested. Many thanks for your input!
http://www.dostips.com/DtCodeCmdLib.php#Function.toHex

:wink:

Re: Enhanced toHex function

Posted: 30 Mar 2011 22:19
by dbenham
Oooh! :D I like the bit manipulation in the final version!

Very clean and efficient.

I think in my own version I will add a leading /S option to the parameter list. If passed then I'll shift the arguments and activate the code to strip leading zeros.

Dave

Re: Enhanced toHex function

Posted: 31 Mar 2011 07:56
by ghostmachine4
Am curious, how many digits of decimal numbers have you tested? Most modern language already support big decimals. This routine can only be used as a toy, not for production.