Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for bin2dec.bat

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

  1. @ECHO OFF
  2. :: Check Windows version: NT 4 or later required
  3. IF NOT "%OS%"=="Windows_NT" GOTO Syntax
  4. :: Check number of command line arguments: 1 and only 1 required
  5. IF     "%~1"=="" GOTO Syntax
  6. IF NOT "%~2"=="" GOTO Syntax
  7. :: Check if the command line argument consists of zeroes and ones only
  8. ECHO "%~1"| FINDSTR /R /B /C:"\"[01][01]*\"$" >NUL || GOTO Syntax
  9.  
  10. :: Initialize the variables
  11. SET Binary=%~1
  12. SET Decimal=0
  13. SET DigVal=1
  14.  
  15. :: Display the initial binary value
  16. SET Binary
  17.  
  18. :Loop
  19. :: Extract the last digit from the binary number
  20. IF %Binary% GTR 1 (
  21. 	SET Digit=%Binary:~-1%
  22. 	SET Binary=%Binary:~0,-1%
  23. ) ELSE (
  24. 	SET /A Digit = %Binary%
  25. 	SET Binary=0
  26. )
  27. :: Add the digit's value to the decimal result
  28. IF %Digit% EQU 1 SET /A Decimal = %Decimal% + %DigVal%
  29. :: Increment the digit's value (multiply by 2)
  30. SET /A DigVal *= 2
  31. :: If the value of the remaining digits is
  32. :: greater than 0, loop to the next iteration
  33. IF %Binary% GTR 0 GOTO Loop
  34.  
  35. :: Clean up aal variables but one
  36. SET Binary=
  37. SET Digit=
  38. SET DigVal=
  39.  
  40. :: Display the decimal result
  41. SET Decimal
  42.  
  43. :: Exit with the decimal result as return code
  44. EXIT /B %Decimal%
  45.  
  46.  
  47. :Syntax
  48. ECHO Bin2Dec.bat,  Version 1.00 for Windows NT 4 and later
  49. ECHO Convert binary numbers to decimal
  50. ECHO.
  51. ECHO Usage:  BIN2DEC  binary_number
  52. ECHO.
  53. ECHO Where:  "binary_number"  is the binary number to be converted
  54. ECHO                          (zeroes and ones only, no prefix nor suffix)
  55. ECHO.
  56. ECHO Notes:  The binary number and the decimal result are displayed as text on
  57. ECHO         screen, and the decimal number is stored in an environment variable
  58. ECHO         named "Decimal", and returned as "errorlevel" (return code); this
  59. ECHO         means errorlevel 0 could mean decimal result 0 or a syntax error.
  60. ECHO         This batch file requires FINDSTR, which is not available in NT 4; for
  61. ECHO         Windows NT 4 use FINDSTR from the Microsoft Windows NT Resource Kit.
  62. ECHO.
  63. ECHO Written by Rob van der Woude
  64. ECHO http://www.robvanderwoude.com
  65.  

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