Shell script to convert binary to decimal
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
binaryConOutput:

output





Please Login to comment...