The Wayback Machine - https://web.archive.org/web/20230130150033/https://www.geeksforgeeks.org/shell-script-to-convert-binary-to-decimal/
Skip to content
Related Articles
Open in App
Not now

Related Articles

Shell script to convert binary to decimal

Improve Article
Save Article
  • Last Updated : 11 Jul, 2022
Improve Article
Save Article

Given a binary number as input, we need to make a conversion from a binary number to its equivalent decimal number.

Examples : 

Input : 1011
Output : 11
Input : 1111
Output : 15

Binary to decimal 

The idea is to retain the decimal number from the binary number, so, take the binary number and traverse from right to left, taking one by one the last digit of the binary number. 

Pick the last digit and multiply by the proper base (power of two) and add it to the final variable (say num).

Repeat this process until the binary number is not equal to zero and then print the result (that is, num).

Example 1: 

n =  101 (Binary number)

num = 1*(2^2) + 0*(2^1) + 1*(2^0) = 6 (resultant decimal)

Example 2: 

n =  1101 (Binary number)

num =1*(2^3) + 1*(2^2) + 0*(2^1) + 1*(2^0) = 13 (resultant decimal)

Here We will extract the decimal number from the given binary number.

# Take input as binary number
echo "Enter Binary Number -"
read n

# function to convert binary to decimal number
function binaryCon(){

    local i=0
    local num=0
    
    # while loop
    while [ $n != 0 ]
    do
    digit=`expr $n % 10`
    num=$(( num + digit * 2**i ))
    n=`expr $n / 10`
    (( ++i ))
    done
    
    # print the resultant decimal number
    echo "Resultant Decimal Number"
    echo "$num"
}

# Function Call
binaryCon

Output:

output

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!