0
0
Bash-scriptingConversionBeginner · 2 min read

Bash Script to Convert Binary to Decimal Number

Use echo $((2#binary_number)) in Bash to convert a binary string to its decimal equivalent, for example: echo $((2#101)) outputs 5.
📋

Examples

Input101
Output5
Input1101
Output13
Input0
Output0
🧠

How to Think About It

To convert binary to decimal in Bash, treat the binary string as a base-2 number and use Bash's arithmetic expansion with the prefix 2# to specify base 2. This tells Bash to interpret the string as binary and convert it to decimal automatically.
📐

Algorithm

1
Get the binary number as input.
2
Use Bash arithmetic expansion with <code>2#</code> prefix to convert binary to decimal.
3
Print the decimal result.
💻

Code

bash
#!/bin/bash
read -p "Enter a binary number: " binary
# Convert binary to decimal
decimal=$((2#$binary))
echo "Decimal value: $decimal"
Output
Enter a binary number: 101 Decimal value: 5
🔍

Dry Run

Let's trace the input '101' through the code

1

Read input

User inputs '101', stored in variable 'binary'

2

Convert binary to decimal

Evaluate $((2#101)) which equals 5

3

Print result

Output 'Decimal value: 5'

binarydecimal
1015
💡

Why This Works

Step 1: Using base prefix

The 2# prefix tells Bash to treat the following number as base 2 (binary).

Step 2: Arithmetic expansion

Bash evaluates $((2#binary)) and converts it to decimal automatically.

Step 3: Output the result

The decimal value is stored in a variable and printed to the user.

🔄

Alternative Approaches

Using bc command
bash
read -p "Enter binary: " binary
decimal=$(echo "ibase=2; $binary" | bc)
echo "Decimal value: $decimal"
Uses external bc tool; useful if arithmetic expansion is limited or for very large binaries.
Manual loop conversion
bash
read -p "Enter binary: " binary
decimal=0
len=${#binary}
for (( i=0; i<len; i++ )); do
  bit=${binary:i:1}
  decimal=$((decimal * 2 + bit))
done
echo "Decimal value: $decimal"
Manually processes each bit; educational but longer and less efficient.

Complexity: O(n) time, O(1) space

Time Complexity

The conversion takes time proportional to the length of the binary string because Bash processes each digit internally.

Space Complexity

Only a few variables are used, so space is constant regardless of input size.

Which Approach is Fastest?

Using Bash arithmetic expansion is fastest and simplest; using bc is slower due to external call; manual loop is slowest but educational.

ApproachTimeSpaceBest For
Bash arithmetic expansionO(n)O(1)Quick and simple conversions
bc commandO(n)O(1)Handling very large binaries or when arithmetic expansion is limited
Manual loopO(n)O(1)Learning and understanding conversion process
💡
Use Bash's built-in arithmetic expansion with 2# prefix for quick binary to decimal conversion.
⚠️
Forgetting to prefix the binary number with 2# causes Bash to treat it as decimal, leading to wrong results.