Bash Script to Convert Hexadecimal to Decimal Number
Use Bash's built-in arithmetic expansion with
$((16#hex_value)) to convert a hexadecimal string to decimal, for example: decimal=$((16#1A)).Examples
Input1A
Output26
InputFF
Output255
Input0
Output0
How to Think About It
To convert a hexadecimal number to decimal in Bash, treat the hex string as a base-16 number and use Bash's arithmetic expansion syntax with
16# prefix. This tells Bash to interpret the following string as hexadecimal and convert it to decimal automatically.Algorithm
1
Get the hexadecimal input as a string.2
Use Bash arithmetic expansion with the prefix <code>16#</code> to convert the hex string to decimal.3
Store or print the decimal result.Code
bash
#!/bin/bash read -p "Enter a hexadecimal number: " hex # Convert hex to decimal decimal=$((16#$hex)) echo "Decimal value: $decimal"
Output
Enter a hexadecimal number: 1A
Decimal value: 26
Dry Run
Let's trace the input '1A' through the code
1
Read input
User inputs '1A', stored in variable hex='1A'
2
Convert hex to decimal
Evaluate $((16#1A)) which converts hex '1A' to decimal 26
3
Print result
Output 'Decimal value: 26'
| hex | decimal |
|---|---|
| 1A | 26 |
Why This Works
Step 1: Using arithmetic expansion
Bash supports arithmetic expansion with $(( )), allowing calculations inside.
Step 2: Base prefix 16#
Prefixing the number with 16# tells Bash to treat the number as base 16 (hexadecimal).
Step 3: Automatic conversion
Bash converts the hex string to decimal automatically inside the arithmetic expansion.
Alternative Approaches
Using printf
bash
read -p "Enter hex: " hex printf "%d\n" 0x$hex
Uses printf to convert hex to decimal; simpler but requires 0x prefix.
Using bc command
bash
read -p "Enter hex: " hex echo "ibase=16; $hex" | bc
Uses bc calculator for conversion; useful if arithmetic expansion is limited.
Complexity: O(1) time, O(1) space
Time Complexity
Conversion is a direct arithmetic operation with no loops, so it runs in constant time.
Space Complexity
Only a few variables are used, so space usage is constant.
Which Approach is Fastest?
Bash arithmetic expansion is fastest and simplest; printf and bc add overhead but offer alternatives.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Bash arithmetic expansion | O(1) | O(1) | Simple scripts, fastest |
| printf command | O(1) | O(1) | Quick one-liners, requires 0x prefix |
| bc command | O(1) | O(1) | Complex calculations, external tool |
Always ensure your hex input contains valid hexadecimal characters (0-9, A-F).
Forgetting to prefix the hex number with
16# inside arithmetic expansion causes errors.