Skip navigation

JSI Tip 5842. How do I convert a decimal number to hexadecimal?


NOTE: See How can I convert a hexadecimal number to decimal, or a decimal number to hexadecimal, in a batch?


I have scripted a general purpose routine, Dec2Hex.bat, to convert a decimal number into a hexadecimal number.

The syntax for using Dec2Hex.bat is:

Dec2Hex DecimalNumber HexVariable HexNumberCharacters

where:

DecimalNumber The decimal number to convert. It must be in the range of -2147483647 to 2147483647.
HexVariable The call directed environment variable that will contain the hexadecimal number.
HexNumberCharacters The call directed numeric environment variable that will contain the number of characters in the hexadecimal number. If HexNumberCharacters has a data value of 0, a syntax error occurred.

Examples:

call Dec2Hex 0 Hex length would set hex to 0 and length to the number 1.

call Dec2Hex 16 Hex length would set hex to 10 and length to the number 2.

call Dec2Hex 2147483647 Hex length would set hex to 7FFFFFFF and length to the number 8.

call Dec2Hex -1 Hex length would set hex to FFFFFFFF and length to the number 8.

Dec2Hex.bat contains:

@echo off
setlocal
if \{%3\}

\{\} goto syntax set work=%1 set neg=%work:~0,1% set /a divid=%1 if "%neg%" EQU "-" set /a divid=%work:~1,10% - 1 if "%neg%" EQU "-" set /a divid=0x7FFFFFFF - %divid% set /a cnt=8 set dword0=0 set dword1=0 set dword2=0 set dword3=0 set dword4=0 set dword5=0 set dword6=0 set dword7=0 set Hex=0123456789ABCDEF :loop set /a mod=%divid% ^%% 16 set /a quot=%divid% / 16 set /a divid=%quot% set /a cnt=%cnt% - 1 call set dword%cnt%=%%hex:~%mod%^,1%% if %quot% EQU 0 goto finish goto loop :syntax @echo Syntax Call Dec2Hex DecimalValue HexName HexChars endlocal If not \{%3\}

\{\} set /a %3=0 goto :EOF :finish if "%neg%" EQU "-" goto neg%dword0% :finish1 set divid=%dword0%%dword1%%dword2%%dword3%%dword4%%dword5%%dword6%%dword7% set /a chars=8 - %cnt% call set ans=%%divid:~%cnt%^,%chars%%% endlocal&set %2=%ans%&set /a %3=%chars% goto :EOF :neg0 set dword0=8 goto nega :neg1 set dword0=9 goto nega :neg2 set dword0=A goto nega :neg3 set dword0=B goto nega :neg4 set dword0=C goto nega :neg5 set dword0=D goto nega :neg6 set dword0=E goto nega :neg7 set dword0=F :nega set /a cnt=0 goto finish1


Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish