0
0
Bash-scriptingConversionBeginner · 2 min read

Bash Script to Convert Decimal to Hexadecimal

Use printf '%X\n' decimal_number in Bash to convert a decimal number to its hexadecimal representation.
📋

Examples

Input10
OutputA
Input255
OutputFF
Input0
Output0
🧠

How to Think About It

To convert decimal to hexadecimal in Bash, think of the decimal number as a base-10 value that you want to express in base-16. Bash's built-in printf command can format numbers in hexadecimal using the %X format specifier, which automatically handles the conversion.
📐

Algorithm

1
Get the decimal number input from the user or as an argument.
2
Use the <code>printf</code> command with the <code>%X</code> format specifier to convert the decimal number to hexadecimal.
3
Print the resulting hexadecimal value.
💻

Code

bash
#!/bin/bash

# Read decimal number from input
read -p "Enter a decimal number: " decimal

# Convert to hexadecimal and print
printf '%X\n' "$decimal"
Output
Enter a decimal number: 255 FF
🔍

Dry Run

Let's trace converting decimal 255 to hexadecimal using the script.

1

Input decimal number

User enters 255

2

Run printf command

printf '%X\n' 255

3

Output hexadecimal

FF

Decimal Inputprintf CommandHexadecimal Output
255printf '%X\n' 255FF
💡

Why This Works

Step 1: Using printf for formatting

The printf command formats output; %X tells it to convert the number to uppercase hexadecimal.

Step 2: Input as decimal

The input number is treated as decimal by default, so no extra conversion is needed before formatting.

Step 3: Output is hexadecimal

The result printed is the hexadecimal equivalent of the decimal input.

🔄

Alternative Approaches

Using bc command
bash
read -p "Enter decimal: " dec
hex=$(echo "obase=16; $dec" | bc)
echo "$hex"
This uses the bc calculator for conversion; it supports uppercase letters by default and works well for large numbers but requires bc installed.
Using printf with lowercase hex
bash
read -p "Enter decimal: " dec
printf '%x\n' "$dec"
This prints hexadecimal in lowercase letters instead of uppercase.

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

Time Complexity

The conversion uses built-in formatting 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?

Using printf is fastest and simplest; bc is flexible but slower due to external process.

ApproachTimeSpaceBest For
printf '%X'O(1)O(1)Simple, fast conversion
bc commandO(1)O(1)Large numbers, uppercase hex, flexible
printf '%x'O(1)O(1)Lowercase hex output
💡
Use printf '%X\n' number for quick decimal to uppercase hexadecimal conversion in Bash.
⚠️
Beginners often forget to quote the variable in printf, which can cause errors if the input is empty or contains spaces.