-
-
Save ijprest/1207832 to your computer and use it in GitHub Desktop.
@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 |
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
Should work well with positive numbers up to 2^31-1. It tries to handle negative numbers (two's complement), but it's a bit of a hack, and it breaks down with larger negatives.