Created
September 10, 2011 02:07
-
-
Save ijprest/1207832 to your computer and use it in GitHub Desktop.
CMD Batch file conversion of a decimal number to hex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@echo off & setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION | |
set LOOKUP=0123456789abcdef &set HEXSTR=&set PREFIX= | |
if "%1"=="" echo 0&goto :EOF | |
set /a A=%* || exit /b 1 | |
if !A! LSS 0 set /a A=0xfffffff + !A! + 1 & set PREFIX=f | |
:loop | |
set /a B=!A! %% 16 & set /a A=!A! / 16 | |
set HEXSTR=!LOOKUP:~%B%,1!%HEXSTR% | |
if %A% GTR 0 goto :loop | |
echo %PREFIX%%HEXSTR% | |
goto :EOF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is awesome. I took the liberty to change it from a batch file into a call function in a batch file. This way, you can easily included it with any batch file. Way to go.. thumbs up
Here is the modification:
@echo off
setlocal EnableDelayedExpansion
set DecValue=32
call :ConvertDecToHex %DecValue% HexValue
echo HexValue = %HexValue%
pause
:End
Exit
:: A function to convert Decimal to Hexadecimal
:: you need to pass the Decimal as first parameter
:: and return it in the second
:: This function needs setlocal EnableDelayedExpansion to be set at the start if this batch file
:: Refer to https://gist.github.com/ijprest/1207832
:ConvertDecToHex
set LOOKUP=0123456789abcdef
set HEXSTR=
set PREFIX=
if "%1" EQU "" (
set "%2=0"
Goto:eof
)
set /a A=%1 || exit /b 1
if !A! LSS 0 set /a A=0xfffffff + !A! + 1 & set PREFIX=f
:loop
set /a B=!A! %% 16 & set /a A=!A! / 16
set HEXSTR=!LOOKUP:~%B%,1!%HEXSTR%
if %A% GTR 0 Goto :loop
set "%2=%PREFIX%%HEXSTR%"
Goto:eof
:: End of :ConvertDecToHex function