Skip navigation

JSI Tip 8968. How can I convert a hexadecimal number to decimal, or a decimal number to hexadecimal, in a batch?


Using Hex2Dec freeware from SysInternals, I have scripted HexDec.bat to convert a hexadecimal number to decimal, or a decimal number to hexadecimal.

The syntax for using HexDec.bat is:

call HexDec NumberToBeConverted ConvertedNumber

Where:

NumberToBeConverted  is either a decimal number, or a hexadecimal number. If the string starts with x, or 0x, it is a hexadecimal number.

ConvertedNumber is a call directed environment variable that will contain the results of the conversion. If NumberToBeConverted is hexadecimal, the ConvertedNumber will be an arithmetic environment variable.
If NumberToBeConverted is decimal, the ConvertedNumber will start with 0x.

Examples:

call HexDec 1024 hexvar
will set the hexvar environment variable to 0x400.

If you then use call HexDec %hexvar% decvar
then decvar will be an arithmetic environment variable containing 1024.

HexDec.bat contains:

@echo off
if \{%2\}==\{\} @echo Syntax: HexDec From To&goto :EOF
set $HexDec$=N
for /f "Tokens=*" %%h in ('@echo %1^|FIND /I "X"') do (
 set $HexDec$=Y
)
for /f "Skip=5 Tokens=1,3" %%a in ('hex2dec.exe %1') do (
 if "%$HexDec$%" EQU "N" (
 set %2=%%b
 ) ELSE (
 set /a %2=%%b
 )
set $HexDec$=
)



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