Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for dec2hex.bat

(view source code of dec2hex.bat as plain text)

  1. @ECHO OFF
  2. SETLOCAL ENABLEDELAYEDEXPANSION
  3. :: The following SET /A line cuts the input range in half (0x7FFFFFFF) because negative numbers (0x80000000 and up) are ignored.
  4. :: Using SET /A also allows calculations and/or octal and/or hexadecimal numbers.
  5. :: 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).
  6. :: PING cannot handle 0xFFFFFFFF because it is the DHCP broadcast address.
  7. SET /A Decimal = %* +0 >NUL 2>&1 || GOTO Syntax
  8. IF %Decimal% LSS 0 GOTO Syntax
  9. 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 (
  10. 	FOR %%B IN (%%A) DO SET FourOctets=%%B
  11. )
  12. SET Hexadecimal=0x
  13. FOR %%A IN (%FourOctets:.= %) DO (
  14. 	CALL :D2H %%A
  15. )
  16. Set Decimal
  17. SET Hexadecimal
  18. ENDLOCAL
  19. GOTO:EOF
  20.  
  21.  
  22. :D2H
  23. SET Convert=0123456789ABCDEF
  24. :: Split the number (0-255) into 2 single digits and convert each digit to hexadecimal
  25. SET /A MSB = %1 / 16
  26. SET MSB=!Convert:~%MSB%,1!
  27. SET /A LSB = %1 %% 16
  28. SET LSB=!Convert:~%LSB%,1!
  29. :: Append to hex value
  30. SET Hexadecimal=%Hexadecimal%%MSB%%LSB%
  31. GOTO:EOF
  32.  
  33.  
  34. :Syntax
  35. ECHO.
  36. ECHO Dec2Hex.bat,  Version 3.00
  37. ECHO Convert a decimal number to "7.5" digit hexadecimal
  38. ECHO.
  39. ECHO Usage:  DEC2HEX  number
  40. ECHO.
  41. ECHO Where:  number   is a 32-bit positive integer or calculation
  42. ECHO                  (0..2,147,483,647 or 0x00000000..0x7FFFFFFF)
  43. ECHO.
  44. ECHO This batch file first uses SET /A to convert the command line arguments to
  45. ECHO a 32-bit integer, allowing the use of decimal, octal or hexadecimal numbers,
  46. ECHO as well as calculations on the command line, e.g. "DEC2HEX 80 * 0x00200000".
  47. ECHO As a side-effect, this does limit the input range from 0..2,147,483,647
  48. ECHO (0..0x7FFFFFFF), because higher integers are interpreted as negative numbers.
  49. ECHO Next, PING is used to split up the resulting number into 4 2-digit hexadecimal
  50. ECHO numbers (0x00..0xFF), that are each displayed as a decimal number (0..255).
  51. ECHO These 4 decimal numbers are then converted to 2-digit hexadecimal by the rest
  52. ECHO of the batch file.
  53. ECHO.
  54. ECHO Written by Rob van der Woude
  55. ECHO https://www.robvanderwoude.com
  56. ENDLOCAL
  57. EXIT /B 1
  58.  

page last modified: 2024-04-16; loaded in 0.0058 seconds