Skip to content

Instantly share code, notes, and snippets.

@ijprest
Created September 10, 2011 02:07
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ijprest/1207832 to your computer and use it in GitHub Desktop.
Save ijprest/1207832 to your computer and use it in GitHub Desktop.
CMD Batch file conversion of a decimal number to hex
@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
@ijprest
Copy link
Author

ijprest commented Sep 10, 2011

@ijprest
Copy link
Author

ijprest commented Sep 10, 2011

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.

@AkramAlhinnawi
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment