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

Jerold Schulman

January 23, 2005

1 Min Read
ITPro Today logo in a gray background | ITPro Today


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 offif {%2}=={} @echo Syntax: HexDec From To&goto :EOFset $HexDec$=Nfor /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$=)



Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like