Binary to Decimal Converter in Bash

 

Binary to Decimal Converter

This page contains a Bash script that converts binary numbers to decimal. Below is the complete code along with detailed documentation.

Bash Script


#!/bin/bash

# Function to convert binary to decimal
# Usage: binary_to_decimal 
binary_to_decimal() {
    local binary=$1
    local decimal=0
    local base=1
    local length=${#binary}

    # Loop through each digit in the binary number
    for (( i=$length-1; i>=0; i-- )); do
        digit=${binary:$i:1}
        if [ $digit -eq 1 ]; then
            decimal=$((decimal + base))
        fi
        base=$((base * 2))
    done

    echo $decimal
}

# Main script execution
# Check if the user has provided an input
if [ $# -eq 0 ]; then
    echo "Usage: $0 "
    exit 1
fi

# Convert binary to decimal
binary_number=$1
decimal_number=$(binary_to_decimal $binary_number)
echo "Binary: $binary_number"
echo "Decimal: $decimal_number"

Explanation

The above Bash script converts a binary number provided as a command-line argument to its decimal equivalent. Here is a detailed explanation of the program structure:

  • binary_to_decimal function: This function takes a binary number as an argument and converts it to a decimal number. It initializes decimal to 0 and base to 1. The function loops through each digit of the binary number from right to left, updating the decimal value accordingly.
  • Main script execution: The main part of the script checks if a binary number is provided as an argument. If not, it displays a usage message and exits. If a binary number is provided, it calls the binary_to_decimal function and prints the result.

Usage

To use this script, save it to a file (e.g., binary_to_decimal.sh), make it executable, and run it with a binary number as an argument:


chmod +x binary_to_decimal.sh
./binary_to_decimal.sh 1011
    

The script will output:


Binary: 1011
Decimal: 11
    

 

Explanation of the Bash Script

  1. Function Definition:
    • binary_to_decimal function: This function takes a binary number as an argument and converts it to a decimal number.
    • It initializes decimal to 0 and base to 1.
    • It loops through each digit of the binary number from right to left. If the digit is 1, it adds the current base value to decimal.
    • It updates the base by multiplying it by 2 after each iteration.
  2. Main Script Execution:
    • Checks if a binary number is provided as an argument.
    • If no argument is provided, it prints a usage message and exits.
    • If an argument is provided, it calls the binary_to_decimal function and prints the binary and decimal numbers.
  3. Usage:
    • Save the script to a file, make it executable, and run it with a binary number as an argument to see the conversion result.

Leave a Reply

Your email address will not be published. Required fields are marked *