Bash Script to Convert Decimal to Binary Number
while [ $decimal -gt 0 ]; do binary=$((decimal % 2))$binary; decimal=$((decimal / 2)); done to convert decimal to binary.Examples
How to Think About It
Algorithm
Code
#!/bin/bash read -p "Enter a decimal number: " decimal if [ "$decimal" -eq 0 ]; then echo 0 exit fi binary="" while [ $decimal -gt 0 ]; do remainder=$((decimal % 2)) binary="$remainder$binary" decimal=$((decimal / 2)) done echo "$binary"
Dry Run
Let's trace the decimal number 5 through the code
Initial input
decimal = 5, binary = ""
First loop iteration
remainder = 5 % 2 = 1, binary = "1", decimal = 5 / 2 = 2
Second loop iteration
remainder = 2 % 2 = 0, binary = "01", decimal = 2 / 2 = 1
Third loop iteration
remainder = 1 % 2 = 1, binary = "101", decimal = 1 / 2 = 0
Loop ends
decimal = 0, final binary = "101"
| decimal | remainder | binary |
|---|---|---|
| 5 | 1 | 1 |
| 2 | 0 | 01 |
| 1 | 1 | 101 |
Why This Works
Step 1: Divide and get remainder
Each division by 2 gives a remainder of 0 or 1, which is a binary digit.
Step 2: Build binary string
Prepending the remainder builds the binary number from least significant bit to most.
Step 3: Stop when zero
When the decimal number reaches zero, all binary digits are collected.
Alternative Approaches
read -p "Enter decimal: " decimal printf "%b\n" "$(echo "obase=2; $decimal" | bc)"
read -p "Enter decimal: " decimal printf '%d in binary is %s\n' "$decimal" "$(echo "obase=2; $decimal" | bc)"
Complexity: O(log n) time, O(log n) space
Time Complexity
The loop runs once for each binary digit, which is proportional to log base 2 of the decimal number.
Space Complexity
The binary string grows with the number of bits, so space is proportional to log base 2 of the input.
Which Approach is Fastest?
The manual loop is efficient and requires no external tools; using bc is simpler but depends on external command.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual loop with division | O(log n) | O(log n) | No dependencies, educational |
| Using bc command | O(log n) | O(log n) | Quick and simple if bc is available |