Shell script to convert binary to decimal
Last Updated :
12 Dec, 2023
Binary and decimal are two fundamental number systems used in computing. While humans typically interact with decimal numbers (0-9), computers internally store and process data using binary digits (0s and 1s). Converting between these systems is often necessary when working with computer programs or manipulating data. This article explores how to write a shell script that converts a binary number to its decimal equivalent.
Understanding the Conversion Process
Converting a binary number to decimal involves multiplying each binary digit by its corresponding power of 2, starting from the rightmost digit as the exponent and increasing by 1 for each subsequent digit to the left. Finally, we sum the products of these individual multiplications to obtain the decimal equivalent.
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).
For example, let's consider the binary number
Example 1 :
n = 10101 (Binary number)
- Rightmost digit (1) * 2^0 = 1
- Second digit (0) * 2^1 = 0
- Third digit (1) * 2^2 = 4
- Fourth digit (0) * 2^3 = 0
- Leftmost digit (1) * 2^4 = 16
Summing these values: 1 + 0 + 4 + 0 + 16 = 21
Therefore, the decimal equivalent of 10101 is 21.
Example 2:
n = 101 (Binary number)
num = 1*(2^2) + 0*(2^1) + 1*(2^0) = 6 (resultant decimal)
Example 3:
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.
Shell Script to Convert Binary to Decimal
#!/bin/bash
# Take input as binary number
echo "Enter Binary Number: "
read n
# Validate input
if [[ ! "$n" =~ ^[01]+$ ]]; then
echo "Error: Invalid binary number."
exit 1
fi
# Initialize variables
i=0
num=0
# Convert binary to decimal
while [ $n -ne 0 ]; do
digit=$((n % 10))
num=$((num + digit * 2**i))
n=$((n / 10))
let "i++"
done
# Print the result
echo "Resultant Decimal Number: $num"
Step by Step Explanation of the Shell Script to Convert Binary to Decimal
1. Setting up the script:
#!/bin/bash
: This tells the system to use the bash interpreter to run the script.echo "Enter Binary Number: "
: This displays a message asking the user to enter a binary number.read n
: This reads the user's input and stores it in the variable n
.
2. Validating the input:
if [[ ! "<span class="math-inline">n" \=\~ ^\[01\]\+</span> ]]; then
: This checks if the input n
contains only 0s and 1s using regular expressions.!
: This negates the expression, meaning it checks for the absence of valid characters.^
: This matches the beginning of the string.[01]+
: This matches one or more repetitions of 0s or 1s.$
: This matches the end of the string.
echo "Error: Invalid binary number."
: If the input is invalid, this displays an error message.exit 1
: This exits the script with an error code of 1.
3. Initializing variables:
i=0
: This initializes the variable i
to 0. This variable will be used as a counter later.num=0
: This initializes the variable num
to 0. This variable will store the final decimal number.
4. Converting binary to decimal:
while [ $n -ne 0 ]; do
: This starts a loop that continues until the value of n
becomes 0.<span class="math-inline">n \-ne 0\
: This checks if `n` is not equal to 0. * `digit=((n % 10)): This calculates the rightmost digit of the binary number stored in
nand assigns it to the variable
digit`.%
: This is the modulus operator which gives the remainder of dividing n
by 10.<span class="math-inline">\(\(\.\.\.\)\)\
: This is a bash expression used for arithmetic operations. * `num=((num + digit * 2**i)): This adds the value of
digitmultiplied by 2 raised to the power of
ito the variable
num`.2**i
: This raises 2 to the power of i
.+
: This adds the two values.
n=$((n / 10))
: This removes the rightmost digit from the binary number stored in n
./
: This is the division operator.
let "i++"
: This increments the value of the variable i
by 1.done
: This ends the loop.
5. Printing the result:
echo "Resultant Decimal Number: $num"
: This displays the final decimal number stored in the variable num
.
How to execute the bash files?
Write the bash code into a text file using text editors. In this example we are using Vim text editor and saving our file with `.sh` extension.
Open terminal and execute the file using below command:
vim Binary.sh
Making Script Executable
chmod +x Binary.sh
Execute the Script
./Binary.sh
Output:
Shell Script to convert binary to decimal
Conclusion
In this article we discussed how to write a shell script to convert binary to decimal . To sum it up, this article is about turning computer language (binary) into numbers we humans use (decimal). It explains the process step by step and gives an easy-to-use script (like a computer recipe) using a program called Bash. The article shows why it's important to understand this conversion, gives examples, and helps people practice it with the provided script. It's like learning a new language and then using a simple tool to speak it.
Similar Reads
Shell Scripting - Creating a Binary file
While working in Linux systems, we have used so many commands on a day-to-day basis. Most of the commands are in the binary format resides under /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, etc directories. As system administrators, we would have to write many shell scripts to do a few tasks or
4 min read
Shell Script To Check For a Valid Floating-Point Value
User Input can be hectic to manage especially if it's about numbers. Let's say you wanted to perform mathematical calculations in your app or script. It's not hard to say that it will have to deal with floating-point numbers. It's easy in many statically typed programming languages but if it has to
4 min read
od command in Linux with example
The od (octal dump) command in Linux is a versatile tool used to display file contents in various formats, with the default being octal. This command is particularly useful for debugging scripts, examining binary files, or visualizing non-human-readable data like executable code. It allows users to
6 min read
How to Use GNU bc (Basic Calculator) in Linux
The Basic calculator (bc) is an arbitrary-precision calculator that you can use as a simple scientific or financial calculator on the command-line interface of your Linux system. The syntax is similar to the C programming language. You just have to type the following command to see whether bc is alr
3 min read
xxd Command in Linux
xxd is a command-line tool that is primarily used for creating and analyzing hexadecimal dumps from files. It can also be used to reverse the process and convert a hexadecimal dump back into binary form. In this article, let's uncover the practical applications of the "xxd" command in the Linux ecos
9 min read
Binary to Decimal Converter
Binary to Decimal Converter is a free online tool to convert binary to decimal. Converting between binary to decimal is a common task in everyday life. Here, GeeksforGeeks provides a free user-friendly, and efficient online binary decimal Conversion tool to simplify this process and ensure accuracy.
9 min read
Decimal to Binary Converter
The Decimal to Binary Converter is a free, online tool designed to quickly and accurately convert decimal numbers (base 10) to binary numbers (base 2). This tool is especially useful for computer science students, programmers, and anyone who frequently deals with number system conversions. Also, Che
8 min read
Convert Decimal to Binary in C
In this article, we will learn to write a C program to convert a decimal number into a binary number. The decimal number system uses ten digits from 0 to 9 to represent numbers and the binary number system is a base-2 number system that uses only 0 and 1 to represent numbers. Algorithm to Convert De
2 min read
Convert Binary to Decimal in C
In this article, we will learn how to write a C program to convert the given binary number into an equivalent decimal number. Binary numbers are expressed in base 2 ( 0, 1 ) and decimal numbers are expressed in base 10 ( 0-9 ). Algorithm to Convert Binary Numbers to DecimalThe idea is to extract the
3 min read
Binary to Decimal Number Converter
Binary to Decimal Converter is a powerful tool that transforms binary numbers (base-2) into decimal numbers (base-10). iframe {width: 700px; height: 500px;} @media (max-width: 780px) {.article--viewer .a-wrapper .content .text iframe {max-width: 100%; min-height: 700px; height: auto;}} @media (max-w
2 min read