(view source code of dec2hex.bat as plain text)
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
:: The following SET /A line cuts the input range in half (0x7FFFFFFF) because negative numbers (0x80000000 and up) are ignored.
:: Using SET /A also allows calculations and/or octal and/or hexadecimal numbers.
:: By replacing the SET /A command by other input evaluations, you can extend the input range to 4,294,967,294 (0xFFFFFFFE or 2**32 - 2).
:: PING cannot handle 0xFFFFFFFF because it is the DHCP broadcast address.
SET /A Decimal = %* +0 >NUL 2>&1 || GOTO Syntax
IF %Decimal% LSS 0 GOTO Syntax
FOR /F "delims=:" %%A IN ('PING.EXE %Decimal% -n 1 -w 1 2^>NUL ^| FINDSTR.EXE /R /E /C:"[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*:"') DO (
FOR %%B IN (%%A) DO SET FourOctets=%%B
)
SET Hexadecimal=0x
FOR %%A IN (%FourOctets:.= %) DO (
CALL :D2H %%A
)
Set Decimal
SET Hexadecimal
ENDLOCAL
GOTO:EOF
:D2H
SET Convert=0123456789ABCDEF
:: Split the number (0-255) into 2 single digits and convert each digit to hexadecimal
SET /A MSB = %1 / 16
SET MSB=!Convert:~%MSB%,1!
SET /A LSB = %1 %% 16
SET LSB=!Convert:~%LSB%,1!
:: Append to hex value
SET Hexadecimal=%Hexadecimal%%MSB%%LSB%
GOTO:EOF
:Syntax
ECHO.
ECHO Dec2Hex.bat, Version 3.00
ECHO Convert a decimal number to "7.5" digit hexadecimal
ECHO.
ECHO Usage: DEC2HEX number
ECHO.
ECHO Where: number is a 32-bit positive integer or calculation
ECHO (0..2,147,483,647 or 0x00000000..0x7FFFFFFF)
ECHO.
ECHO This batch file first uses SET /A to convert the command line arguments to
ECHO a 32-bit integer, allowing the use of decimal, octal or hexadecimal numbers,
ECHO as well as calculations on the command line, e.g. "DEC2HEX 80 * 0x00200000".
ECHO As a side-effect, this does limit the input range from 0..2,147,483,647
ECHO (0..0x7FFFFFFF), because higher integers are interpreted as negative numbers.
ECHO Next, PING is used to split up the resulting number into 4 2-digit hexadecimal
ECHO numbers (0x00..0xFF), that are each displayed as a decimal number (0..255).
ECHO These 4 decimal numbers are then converted to 2-digit hexadecimal by the rest
ECHO of the batch file.
ECHO.
ECHO Written by Rob van der Woude
ECHO https://www.robvanderwoude.com
ENDLOCAL
EXIT /B 1
page last modified: 2024-04-16; loaded in 0.0058 seconds