Enhanced toHex function

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Enhanced toHex function

#1 Post by dbenham » 27 Mar 2011 22:57

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

DosItHelp
Expert
Posts: 239
Joined: 18 Feb 2006 19:54

Re: Enhanced toHex function

#2 Post by DosItHelp » 30 Mar 2011 20:43

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:

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Enhanced toHex function

#3 Post by dbenham » 30 Mar 2011 22:19

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

ghostmachine4
Posts: 319
Joined: 12 May 2006 01:13

Re: Enhanced toHex function

#4 Post by ghostmachine4 » 31 Mar 2011 07:56

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.

Post Reply