Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for bintodec.bat

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

  1. @ECHO OFF
  2. SETLOCAL
  3. :: Check number of command line arguments: 1 and only 1 required
  4. IF     "%~1"=="" GOTO Syntax
  5. IF NOT "%~2"=="" GOTO Syntax
  6. :: Check if the command line argument consists of zeroes and ones only
  7. FOR /F "delims=01" %%A IN ("%~1") DO GOTO Syntax
  8.  
  9. :: Initialize the variables
  10. SET Binary=%~1
  11. SET BitVal=1
  12. SET Decimal=0
  13.  
  14. :: Display the initial binary value
  15. SET Binary
  16.  
  17. :Loop
  18. SET Bit=%Binary:~-1%
  19. SET Binary=0%Binary:~0,-1%
  20. SET /A Decimal += %BitVal% * %Bit% || GOTO Syntax
  21. SET /A BitVal  *= 2                || GOTO Syntax
  22. IF %Binary% GTR 0 GOTO Loop
  23.  
  24. :: Display the decimal result
  25. SET Decimal
  26.  
  27. :: Exit with the decimal result as return code
  28. ENDLOCAL & EXIT /B %Decimal%
  29.  
  30.  
  31. :Syntax
  32. ECHO.
  33. ECHO BinToDec.bat,  Version 1.00
  34. ECHO Convert binary numbers to decimal
  35. ECHO.
  36. ECHO Usage:  BIN2DEC  binary_number
  37. ECHO.
  38. ECHO Where:  "binary_number"  is a binary number to be converted
  39. ECHO                          (zeroes and ones only, maximum 31 bits)
  40. ECHO.
  41. ECHO Notes:  The binary number and the decimal result are displayed
  42. ECHO         as text on screen, and the decimal number is returned
  43. ECHO         as "errorlevel" (return code).
  44. ECHO         Return code is -1 in case of errors.
  45. ECHO.
  46. ECHO Written by Rob van der Woude
  47. ECHO https://www.robvanderwoude.com
  48. ENDLOCAL
  49. EXIT /B -1
  50.  

page last uploaded: 2021-01-27