Number systems are the foundation of computing. While most everyday work uses Base-10 (Decimal), systems use Base-2 (Binary), Base-8 (Octal), Base-16 (Hexadecimal), and sometimes even Base-36 (which uses digits 0-9 and letters A-Z). A General Base Converter allows you to convert any decimal number into any base from 2 to 36 using a single reusable algorithm.
In this guide, we will demonstrate how to build a universal base converter using the "Repeated Division" method.
The Strategy: Divide and Collect Remainders
To convert a decimal number to Base B.
- Divide the number by B.
- Record the remainder (this is the rightmost digit in the new base).
- Replace the number with the quotient.
- Repeat until the number is 0.
- The result is the remainders read in reverse order.
Implementation Script
@echo off
setlocal enabledelayedexpansion
set /p "dec=Enter decimal number: "
set /p "base=Enter target base (2-36): "
:: 1. Define the Digit Characters (0-9, A-Z)
set "DIGITS=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
:: 2. Validate Base
if !base! LSS 2 (echo [ERROR] Base must be 2-36. & pause & exit /b)
if !base! GTR 36 (echo [ERROR] Base must be 2-36. & pause & exit /b)
:: 3. Handle negative numbers
set "sign="
set "num=!dec!"
if !num! LSS 0 (
set "sign=-"
set /a "num=0 - num"
)
:: 4. Handle zero
if !num! EQU 0 (
set "result=0"
goto :show_result
)
:: 5. Conversion Loop
set "result="
:convert_loop
if !num! EQU 0 goto :show_result
set /a "rem=num %% base"
set /a "num/=base"
:: Get the character for this remainder
set "char=!DIGITS:~%rem%,1!"
:: Prepend it to the result (building right to left)
set "result=!char!!result!"
goto :convert_loop
:show_result
echo.
echo ==========================================
echo DECIMAL: !dec!
echo BASE !base!: !sign!!result!
echo ==========================================
pauseWhy Use a General Base Converter?
- Hexadecimal: Base-16 is used for color codes (
#FF5733), memory addresses, and MAC addresses. - Octal: Base-8 is used for Unix file permissions (
chmod 755). - Base-36: Some URL shorteners and tracking systems use Base-36 to encode long IDs into short, alphanumeric codes.
- Binary: Base-2 for subnet masks, bitwise flags, and low-level debugging.
Important Considerations
Conclusion
Building a universal base converter is one of the most versatile mathematical tools you can add to your scripting toolkit. By mastering the "Divide and Collect Remainders" methodology, you create a single algorithm that handles Binary, Octal, Hex, and any other base with equal ease. This flexibility is invaluable for network analysis, data encoding, and low-level system debugging.