How to Convert Hexadecimal Number to Decimal in Bash

Decimal and hexadecimal are popular number systems. Decimal is base 10, using 10 symbols (0-9), while hexadecimal is base 16. Hexadecimal uses 16 symbols: 0-9 and A-F (or a-f), where A=10, B=11, C=12, D=13, E=14 and F=15. This makes hexadecimal suitable for representing binary data in a more compact and readable form (such as the hex color codes). It often requires converting hexadecimal numbers to decimal ones. Common techniques to convert hex numbers to decimal in Bash are:

  1. Convert hex_number using arithmetic expansion with base conversion:
    echo $((16#hex_number))
  2. Using bc command to convert hex number to decimal:
    echo "ibase=16; hex_number" | bc
  3. Using printf command to find the decimal equivalent of a hex number:
    printf "%d" 0xhex_number
  4. Using perl code to get the decimal of a hex number:
    perl -le 'print hex("hex_number");'
  5. Using Python for getting the decimal equivalent of a hex number:
    python3 -c 'print(int("hex_number", 16))'
  6. Using dc command to convert a hex number to the equivalent decimal:
    dc -e '16i hex_number p'

1. Hex to Decimal Using Base Conversion in Bash

It is easy to convert a number from hexadecimal to decimal using the base conversion technique in Bash. The default base for Bash arithmetic is 10, but one can specify a different base using the syntax base#number. Regardless of the original base, arithmetic expansion in Bash always returns the equivalent decimal value after evaluation. Let’s find the decimal equivalent of the hexadecimal number “FF”:

echo $((16#FF))

hex to decimal conversion using arithmetic expansion and base conversionThe image shows that the command returns 255 which is the correct decimal equivalent of “FF”.

To take hexadecimal number from the user and find its equivalent decimal, follow this script:

#!/bin/bash

# Input: Hexadecimal number
read -p "Enter the hexadecimal number: " hex_number
# Conversion using Bash arithmetic
decimal_number=$((16#${hex_number}))

# Output
echo "Equivalent Decimal: $decimal_number"
EXPLANATION

The Bash script takes user input in hexadecimal format. $((16#${hex_number})) converts the given hexadecimal number into a decimal number using arithmetic expansion and base conversion.

Bash script to convert hex to decimal using arithmetic expansionAs you can see, in the first execution, the user provides A and the program returns 10. In the second execution, the program returns 255 as the decimal conversion of hexadecimal “FF”. In both runs, the program perfectly converts the given hex number to the equal decimal number.

2. Hexadecimal to Decimal Using “bc” Command With “ibase” and “obase”

To convert hexadecimal numbers to decimal using bc (Basic calculator) command, use ibase and obase options to define the input base and output base respectively. The default base in bc is 10. So you don’t need to specify obase when you convert hex to decimal. Look at the following code:

echo "ibase=16; FF" | bc

Here, the output base of the number is not defined explicitly. However, if you want to specify the output base of a number even if it is 10, you can use the code below:

echo "ibase=16;obase=A;1A" | bc

Notice that, I put A as the value of obase. In bc, Here, A denotes the 10-base number system.bc command to convert hex to decimal in BashI run both codes in the terminal. Both work fine. The first one converts hex “FF” to decimal 255. The second one successfully converts “1A” to decimal 26.

3. Hex to Decimal Using “printf” Command in Bash

The printf command and its format specifiers are enough for converting a hexadecimal number to decimal. Here’s how you can do it:

printf "%d\n" 0xA
printf "%d\n" 0xff
printf "%d\n" 0xFF

The format specifier %d is used to print a decimal integer. \n is a newline character, which adds a line break after printing the number.printf command to convert hex to decimal in BashIn the first command, A is a hexadecimal literal, printf command with its format specifier returns the decimal equivalent of the literal, which is 10.

The next two executions test the command for the literal ff and FF. Both literals have the same meaning to the printf command. They return 255 as the decimal equivalent of ff and FF.

4. Hex to Decimal Conversion Using “perl” Command in Bash

One can execute Perl code in Bash using the perl command with -e option. In Perl, there is a function called hex that takes hexadecimal values and returns corresponding decimal numbers. Look at the simple command below:

perl -le 'print hex("F");'
EXPLANATION

-e enables the user to execute Perl code in Bash. -l prints the result in a new line. Within the print block, the hex function takes hexadecimal input and returns decimal output.

hex to decimal using perl code in BashAs you can see when I provide “F” in the hex function, it returns decimal 15.

5. Hex to Decimal Using Python Utilities in Bash

Once a Python version is installed in the Bash shell, users can execute Python code using the python2 or python3 command. The int function in Python takes two arguments, the first one represents the number and the second one is the base of the number system used in the first argument. The default base is 10. The syntax is:

int(x, base=10)

One can convert a hex number to decimal using the above syntax. Look at the code below:

python -c 'print(int("FF", 16))'

The above example converts the hexadecimal literal “FF” to its decimal equivalent, which is 255.Python for converting hex number to decimalI use the code for finding the decimal of hex literal “F”, “FF” and “A”. Equivalent decimals of those hex literals are displayed in the image above.

6. Using “dc” Command for Hex to Decimal Conversion in Bash

The dc (desk calculator) command can convert the hex number to decimal. The  -e option of this command indicates that the string followed by the command name should be treated as an expression.

dc -e '16i F p'
EXPLANATION

In the above command, I set the input base to hexadecimal (base 16) with 16i. “F” is the hexadecimal number needed to convert. Finally, p is for printing the converted value.

dc command to convert hex number to decimalThe command returns 15 as the equivalent decimal of hexadecimal “F”.

7. Ruby Code for Hex to Decimal Conversion in Bash

Ruby is a programming language. Bash users can easily run ruby code in a Bash shell. To convert a hex number to a decimal follow the ruby code below:

ruby -e 'p "FF".to_i(16)'
EXPLANATION

ruby command with -e option makes the ruby code executable in Bash shell. 'p "FF".to_i(16)' indicates that the string “FF” is in hexadecimal format. p is used to print the converted result in the console.

hex to decimal conversion using ruby codeWhen the hexadecimal literal “FF” is passed to the command, it returns 255 as the output.

NOTE: If ruby is not installed in the system, install it using the following code:

sudo apt install ruby

8. Node.js for Converting Hexadecimal Numbers to Decimal in Bash

Javascript has a function called parseInt that can convert hex numbers to decimal. Fortunately, Bash users can run Javascript code in the shell. Here is a simple code that converts hexadecimal “FF” to its decimal value 255.

node -e "console.log(parseInt('FF', 16))"
EXPLANATION

node -e allows the user to execute Javascript code in the Bash shell. parseInt('FF', 16) converts the string ‘FF’ from hexadecimal (base-16) to its decimal equivalent. Then console.log(...) prints the decimal result to the console.

hex to decimal conversion using node.js

NOTE: To install node.js in your system, use the code below:

sudo apt install nodejs

9. Rhino to Convert Hexadecimal Numbers to Decimal in Bash

One can pass a heredoc to rhino and convert a hex number to decimal. Here’s how:

rhino <<EOF
print(parseInt('FF', 16))
EOF
EXPLANATION

A heredoc is passed to rhino. The heredoc includes the parseInt function that takes hexadecimal input with base. The return of this function is the decimal equivalent of the hex literal.

rhino code for hex to decimal conversion in BashAs you can see, the rhino code converts the hexadecimal “FF” to the decimal equivalent 255.

NOTE: To install rhino in your system use the following code:

sudo apt install rhino

10. User-Defined Algorithm for Converting Hex to Decimal

Apart from the tools and commands, one can utilize full-fledged Bash programming to define a function for hex-to-decimal conversion. The following function is written from scratch to convert a hex number to decimal:

#!/bin/bash

declare -A hex_digit_val=(
[0]=0 [1]=1 [2]=2 [3]=3
[4]=4 [5]=5 [6]=6 [7]=7
[8]=8 [9]=9 [a]=10 [b]=11
[c]=12 [d]=13 [e]=14 [f]=15
)

hex_to_decimal() {
local hex=${1,,}  # Convert to lowercase to handle both upper and lower case hex
local base
local dec=0

for ((i = 0; i < ${#hex}; i++)); do
base=${hex:$i:1}
dec=$((dec * 16 + hex_digit_val[$base]))
done
echo $dec
}

# Example usage
result=$(hex_to_decimal "1A")
echo $result
EXPLANATION

The script first defines an associate array to map the hexadecimal symbols to their corresponding decimal symbols.

Then it defines a function called hex_to_decimal. It declares a local variable hex and assigns the value ${1,,} to it. ,, syntax converts the variable to lowercase, ensuring that the function can handle both uppercase and lowercase hex characters. In addition, the function declares a local variable base that will be used to store each individual hex digit during the conversion. Moreover, a local variable dec is initially set to 0. This variable will store the decimal equivalent of the hex number.

Next, it initiates a for loop that iterates through each character in the hexadecimal string. ${hex:$i:1} retrieves the current hex digit at position $i and assigns it to the variable base. $((dec * 16 + hex_digit_val[$base])) updates the decimal equivalent by multiplying the current value by 16 and adding the decimal value of the current hex digit. The decimal values are obtained from an array defined earlier in the script. Finally, echo $dec prints the final decimal equivalent after the conversion.

User defined algorithm for hex to decimal conversion in BashI ran the script multiple times to get the decimal of “FF” and “1A”. The program returns 255 and 26 as the hexadecimal of “FF” and “1A” respectively.

A Simple Function for Converting Hex to Decimal and Vice-Versa

At this point, you know all the basic techniques of converting a hexadecimal number into the equivalent decimal. Now, I want to show you a tricky function that can be useful for converting hexadecimal to decimal as well as decimal to hex.

#!/bin/bash

h2d(){
echo "ibase=16; $@" | bc
}
d2h(){
echo "obase=16; $@" | bc
}

read -p "Enter the hexadecimal number to convert: " hex_num
decimal_result=$(h2d "$hex_num")
echo "Decimal equivalent of $hex_num is: $decimal_result"
read -p "Enter the decimal number to convert: " deci_num
hexadecimal_result=$(d2h "$deci_num")
echo "Hexadecimal equivalent of $deci_num is: $hexadecimal_result"
EXPLANATION

The script defines two functions for converting hexadecimal numbers to decimal numbers and decimal numbers to hexadecimal respectively. The bc command takes hexadecimal input using ibase=16 and converts it as a decimal number due to the default decimal base setting in bc.

Conversely, the d2h function sets the output base of bc to 16. So, the decimal input given to this function returns a hexadecimal output.

Simple conversion function of hex to decimalHere, the decimal output for the hexadecimal input 1A is 26. Besides, the hex output for the decimal input 255 is FF.

Converting A list of Hexadecimal Numbers to Decimal in Bash

Sometimes it’s necessary to convert multiple hex numbers or a list of hex numbers into decimals. To convert a list of hexadecimal numbers into decimals use a loop to iterate over each number of the list. Take the following list of hexadecimal numbers in hex_numbers.txt file as an example:

# hex_numbers.txt
D8E4
FF2B
1A
4C91A7
8D3F12B

I use a while loop to convert each hexadecimal number of the list into decimals. Look at the script below for better understanding:

#!/bin/bash

echo "Equivalent decimal numbers:"

# Read the file line by line
while IFS= read -r line; do
# Convert hexadecimal to decimal
decimal=$(echo "ibase=16; $line" | bc)
echo "$decimal"
echo

done < hex_numbers.txt
EXPLANATION

The script reads the list of hexadecimal numbers line by line. For each line, it utilizes the echo command to pass the hexadecimal number to the bc command with ibase=16 to specify hexadecimal input. The resulting decimal value is assigned to a variable and then printed as the equivalent decimal of the corresponding hexadecimal number.

Converting a list of hex numbers to decimalAs you can see, the program converts all the hexadecimal numbers of the list into their decimal equivalent.

Conclusion

In conclusion, users can work seamlessly with different numerical bases in the Bash shell. So hex-to-decimal conversion in Bash is fairly easy. To do the task, you can adapt any technique discussed in this article. Hope you can choose the best way to convert your hex numbers to decimal.

People Also Ask

How to convert decimal numbers to hex in Bash?

To convert decimal numbers to hex in Bash, use the printf command with %x format specifier. For example:

echo $(printf "%x" 255)

Converting decimal to hex using printf in BashLowercase x returns lowercase hex literal whereas uppercase X returns uppercase hex literal as you can see in the image.

Does hex number system use a decimal point?

No. The hexadecimal number system does not use a decimal point. The representation of values in hex is integer-based, and there is no explicit decimal point. If fractional values need to be represented, it’s typically done by using a whole number part and a separate fractional part, rather than a decimal point within the hex number itself.

What is the limit of Bash hex to decimal conversion?

Bash hex to decimal conversion is limited to 64-bit integers, equivalent to 16 hexadecimal digits. The maximum representable hexadecimal value is 7fffffffffffffff. When a hex number exceeds 16 digits, Bash considers only the last 16 digits for conversion. For example:

echo $((16#1157e470953d0000))
echo $((16#11157e470953d0000))

Limit of hex to decimal conversion in BashThe decimals of 1157e470953d0000 and 11157e470953d0000 are the same because the second hex number is 17 digits long, so Bash drops the first character. This makes both the hex number equal so the equivalent decimal.

How to convert hex to binary in Bash?

To convert hex to binary use the bc tool. For instance, use the following code to convert hexadecimal “FF” to binary:

echo "obase=2; ibase=16; FF" | bc

hex to binary conversion in Bash

Related Articles


<< Go Back to Arithmetic Operators in Bash | Bash Operator | Bash Scripting Tutorial

Rate this post
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment